Perl Language

From bibbleWiki
Revision as of 10:22, 10 February 2026 by Iwiseman (talk | contribs) (Flow Control)
Jump to navigation Jump to search

Introduction

Perl is a dynamic, high-level scripting language designed for text processing, system automation, and rapid development. Modern Perl (Perl 5) is widely used for scripting, DevOps, data manipulation, and web services (e.g., Mojolicious). It emphasizes flexibility, expressiveness, and CPAN-driven extensibility.

VS Code and Tooling

VS Code

Perl development in VS Code typically uses:

  • Perl Navigator (LSP features)
  • Syntax highlighting extensions
  • Integrated terminal for running `perl -d` (debugger)

Debugging

Perl does not have a native VS Code debugger. Debugging is done via:

  • `perl -d script.pl`
  • Breakpoints using `BEGIN { $DB::single = 1 }`
  • Mojolicious debugging with `MOJO_REACTOR=POLL perl -d script/app.pl daemon`

Build Tools

Perl does not use Maven/Gradle. Instead:

  • CPAN / cpanminus for dependencies
  • ExtUtils::MakeMaker or Module::Build for packaging
  • Carton for dependency locking

Types

Perl has dynamic typing. Variables are prefixed by sigils.

Scalars

Numbers, strings, booleans all stored in scalars:

  • `$x = 42`
  • `$name = "Iain"`

Numbers

Automatic numeric/string conversion.

Characters

Handled as strings of length 1.

Boolean

Perl has no dedicated boolean type:

  • True = anything not false
  • False = `0`, `""`, `undef`, empty list

Strings

Double-quoted strings interpolate:

  • `"Hello $name"`

Single-quoted do not:

  • `'Hello $name'`

Arrays

Ordered lists:

  • `@items = (1, 2, 3)`
  • `$items[0]`

Hashes

Key/value maps:

  • `%h = (name => "Iain", age => 40)`
  • `$h{name}`

Ranges

  • `(1..10)`
  • `('a'..'z')`

Collections

Filtering and Sorting

grep (Filter)

`grep { $_ > 10 } @list`

map

`map { $_ * 2 } @list`

flatmap (map + flatten)

`map { @$_ } @list_of_arrays`

Combining

`map { ... } grep { ... } @list`

Predicates

Anonymous subs used as predicates: `grep { $_ =~ /abc/ } @list`

References and Complex Structures

Perl uses references for nested structures:

  • Arrayref: `[1,2,3]`
  • Hashref: `{ a => 1 }`

Creating Collections

  • `my @a = qw(a b c)`
  • `my %h = (a => 1, b => 2)`

Flow Control

if

```perl if ($x > 10) { ... } elsif ($x == 10) { ... } else { ... }

given/when (switch)

use feature 'switch'; ```perl given ($x) {

   when (1) { ... }
   when ([2,3]) { ... }
   default { ... }

} ```