🐪 Perl Introduction

🎯 Complete Definition

Perl is a high-level, interpreted, dynamic programming language created by Larry Wall in 1987. Known as the "Swiss Army chainsaw" of scripting, it combines features from C, shell scripting, AWK, and sed. Perl emphasizes practicality (easy to use, efficient, complete) rather than beauty. Its motto is "There's More Than One Way To Do It" (TMTOWTDI).

🔬 Core Characteristics

  • Interpreted: No compilation step; perl executes scripts directly
  • Dynamically Typed: Variables don't require explicit type declarations
  • Context-aware: Scalar vs list context changes behavior
  • Built-in regex: Native, powerful regular expression engine
  • Cross-platform: Runs on 100+ platforms (Unix, Windows, macOS, etc.)
  • CPAN: Comprehensive Perl Archive Network — 250k+ modules
  • Extensible: Inline::C, XS, FFI for interfacing with C/C++

📊 Industry Usage

Perl dominates system administration, bioinformatics, text processing, and legacy web apps (CGI). Used by BBC, Amazon, Booking.com, Cisco. CPAN is the largest repository of open-source modules. Perl 5 remains actively developed (v5.40). Raku is a sister language. Over 2M developers worldwide.

#!/usr/bin/perl use strict; use warnings; print "🐪 Perl 5.40 - CodeOrbitPro Pro Track\n"; print "Perl version: $^V\n"; print "Operating system: $^O\n";

📊 Scalars & Data Types

🎯 Complete Definition

Scalars are single items (number, string, reference). Prefixed with $. Perl has three basic data types: scalars, arrays (prefix @), hashes (prefix %). Types are determined by the sigil, not by declaration. Perl is context-sensitive — a scalar can be interpreted as number or string automatically.

🏷️ Scalar Types

  • Numbers: integers (unlimited precision), floats (double), hex (0xff), octal (0777), scientific (1e6)
  • Strings: single-quoted (literal), double-quoted (interpolation, escapes), heredocs
  • undef: undefined value (like null)
  • References: scalar references to arrays, hashes, etc.
  • Typeglobs: *var represents all variable types with that name

🔧 Context & Magic

Perl automatically converts between numbers and strings. Operators enforce context: + numeric, . string concatenation. Boolean context: undef, 0, "0", "" are false. Special variables: $_ (default), $0 (program name), $! (error), $" (list separator).

use strict; use warnings; my $name = "CodeOrbitPro"; # string my $score = 95; # integer my $pi = 3.14159; # float my $status = undef; # undefined print "$name scored $score\n"; print "Pi is $pi\n"; # Context examples my @array = (1,2,3); my $count = @array; # scalar context → length print "Array length: $count\n"; my $str = 42 . " answers"; # concatenation print $str;

🔢 Operators

🎯 Complete Definition

Perl has a rich set of operators (over 50) categorized by type and precedence. Many operators have both numeric and string variants (e.g. == vs eq). Operators can be overloaded.

📋 Operator Categories

  • Arithmetic: + - * / % ** (exponent)
  • String: . (concat) x (repeat)
  • Comparison numeric: == != < > <= <=> (spaceship)
  • Comparison string: eq ne lt gt le ge cmp
  • Logical: && || // (defined-or) ! and or not
  • Bitwise: & | ^ ~ << >>
  • Assignment: = += -= .= etc.
  • Range: .. (flip-flop in scalar context)
  • Ternary: ? :

⚡ Precedence & Associativity

Highest: ++, -- → **, !, ~, \ → =~, !~ → *, /, %, x → +, -, . → << >> → & → |, ^ → >, >=, <, <=, lt, le, gt, ge → ==, !=, <=>, eq, ne, cmp → &, |, ^ (bitwise) ... Use parentheses for clarity.

my $x = 10; my $y = 3; print "Add: ", $x + $y, "\n"; # 13 print "Exp: ", $x ** $y, "\n"; # 1000 print "Concat: ", $x . $y, "\n"; # 103 print "Repeat: ", "Hi" x 3, "\n"; # HiHiHi print "Numeric compare: ", 10 == 10 ? "equal" : "not", "\n"; print "String compare: ", "10" eq "10" ? "equal" : "not", "\n"; # Defined-or my $value; print $value // "default", "\n"; # default

🔀 Control Flow

🎯 Complete Definition

Perl supports conditional statements (if, unless, else, elsif) and statement modifiers (postfix). Blocks are delimited by curly braces {}. unless is the opposite of if. given/when (Perl 5.10+) provides switch-like functionality.

🏗️ Conditional Structures

  • if (expr) { ... } - execute if true
  • unless (expr) { ... } - execute if false
  • statement if/unless expr; - postfix modifier
  • given (expr) { when (cond) {...} } - switch (experimental)
  • Ternary: expr ? if_true : if_false

🔍 Truthiness & Context

False values: undef, "", 0, "0". Everything else is true. Blocks create lexical scope. do {} blocks return the last evaluated expression.

my $score = 85; if ($score >= 90) { print "Grade A ⭐⭐⭐\n"; } elsif ($score >= 80) { print "Grade B ⭐⭐\n"; } else { print "Grade C or lower\n"; } # unless unless ($score < 60) { print "Passing score\n"; } # Postfix print "Good job!" if $score > 80; # given/when (use feature 'switch') use feature 'switch'; given ($score) { when ($_ >= 90) { print "Excellent\n"; } when ($_ >= 80) { print "Great\n"; } default { print "Keep working\n"; } }

🔄 Loops

🎯 Complete Definition

Perl provides several looping constructs: for, foreach (synonyms), while, until, and do ... while. Loop control: last (break), next (continue), redo (restart iteration without condition check). Labels allow multi-level control.

🏗️ Loop Types

  • for/foreach (LIST) - iterates over a list
  • while (COND) { } - loops while condition true
  • until (COND) { } - loops until condition true
  • do { } while/until (COND) - executes at least once
  • for (init; test; inc) { } - C-style for

⚡ Loop Controls

last exits loop. next skips to next iteration. redo repeats iteration without reevaluating condition. Use labels: OUTER: while(...) { ... next OUTER; }

# foreach my @colors = ("red", "green", "blue"); foreach my $color (@colors) { print "Color: $color\n"; } # C-style for for (my $i=0; $i<5; $i++) { print "i=$i\n"; } # while my $count = 0; while ($count < 3) { print "Count: $count\n"; $count++; } # until my $x = 5; until ($x == 0) { print "x=$x\n"; $x--; } # loop control OUTER: for my $i (1..3) { for my $j (1..3) { last OUTER if $i == 2 && $j == 2; print "($i,$j) "; } } print "\n";

⚙️ Subroutines

🎯 Complete Definition

Subroutines (functions) are defined with sub. Arguments are passed in @_ array. They can be called with or without parentheses. Return value is the last evaluated expression or explicit return. Prototypes (limited) can mimic built-in behavior. Supports recursion, closures, and anonymous subroutines.

🏗️ Subroutine Features

  • sub NAME { ... } - named subroutine
  • my $sub = sub { ... }; - anonymous subroutine
  • Arguments: accessed via $_[0], $_[1] or shift
  • Return: implicit or explicit return
  • Context awareness: wantarray to detect list/scalar context
  • Attributes & prototypes: sub myfunc($$) {...}

🔧 Scope & State

Variables can be lexical (my) or package (our). Persistent variables via state (Perl 5.10). Subroutines are globally visible unless defined lexically.

sub greet { my ($name, $course) = @_; return "Hello $name! Welcome to $course 🚀"; } sub sum { my $total = 0; $total += $_ for @_; return $total; } print greet("CodeOrbitPro", "Perl"), "\n"; print "Sum: ", sum(1..10), "\n"; # Anonymous & closure my $counter = sub { state $count = 0; return ++$count; }; print $counter->(), "\n"; # 1 print $counter->(), "\n"; # 2

📋 Arrays & Lists

🎯 Complete Definition

Array is an ordered list of scalars, prefixed with @. Indexing starts at 0. Arrays grow/shrink dynamically. Lists are comma-separated values, often in parentheses. Arrays provide push, pop, shift, unshift, splice, etc.

🏗️ Array Operations

  • @array = (1,2,3); - assignment
  • $array[0] - access element (scalar)
  • @array[0,1] - array slice (list)
  • $#array - last index
  • push/pop - add/remove at end
  • shift/unshift - add/remove at front
  • splice - replace/remove arbitrary portion
  • qw(red blue green) - quote word list

⚡ Context & Iteration

Array in scalar context returns length. foreach iterates. map and grep transform/filter lists. sort for ordering.

my @languages = qw(Perl Python Ruby); push @languages, "Rust"; print "$languages[0]\n"; # Perl print "Last index: $#languages\n"; # slice my @slice = @languages[1,2]; print "@slice\n"; # Python Ruby # array length in scalar context my $len = @languages; print "Length: $len\n"; # map & grep my @upper = map { uc } @languages; my @filter = grep { /P/ } @languages; print "@upper\n"; # PERL PYTHON RUBY RUST print "@filter\n"; # Perl Python

🔑 Hashes

🎯 Complete Definition

Hash (associative array) is an unordered collection of key-value pairs, prefixed with %. Keys are strings, values are scalars. Efficient lookup (O(1) average). Keys must be unique. Often used for named data structures.

🏗️ Hash Operations

  • %hash = (key => value, ...); - assignment
  • $hash{key} - access value
  • keys %hash - list of keys
  • values %hash - list of values
  • each %hash - iterate (key, value) pairs
  • exists $hash{key} - check key existence
  • delete $hash{key} - remove entry

🔧 Advanced

Hashes flatten in list context. References to hashes allow nested structures. Tied hashes can use database, file etc. Slices: @hash{@keys} to get multiple values.

my %student = ( name => "CodeOrbitPro", xp => 2500, active => 1 ); print $student{name}, "\n"; # CodeOrbitPro # add/update $student{course} = "Perl Pro"; # iteration while (my ($k, $v) = each %student) { print "$k: $v\n"; } # keys, values my @keys = keys %student; my @vals = values %student; print "Keys: @keys\n"; # exists if (exists $student{xp}) { print "XP: $student{xp}\n"; } # hash slice my @fields = qw(name course); my @data = @student{@fields}; print "@data\n";

📝 Regular Expressions

🎯 Complete Definition

Perl's regex engine is one of the most powerful in any language. Regex literals are enclosed in //. Binding operators =~ and !~ apply regex to string. Supports matching m//, substitution s///, and transliteration tr///.

🏗️ Regex Features

  • Metacharacters: . * + ? {} [] () ^ $ |
  • Character classes: \d \w \s \D \W \S, custom [a-z]
  • Quantifiers: * + ? {min,max}
  • Capturing: (...) captures into $1, $2
  • Modifiers: /i (case), /g (global), /m (multiline), /s (single line), /x (extended)
  • Lookarounds: (?=...) (?!...) (?<=...) (?
  • Backtracking control: (?>...), (*PRUNE), etc.

⚡ Performance

Regex compilation can be done with qr//. Use /o to compile once. use re 'debug' for debugging. Unicode and POSIX classes supported.

my $text = "The Perl language is powerful"; if ($text =~ /Perl/) { print "Found Perl\n"; } # substitution $text =~ s/powerful/awesome/; print "$text\n"; # capture my $email = "user@example.com"; if ($email =~ /(\w+)@(\w+\.\w+)/) { print "User: $1, Domain: $2\n"; } # global match my $data = "x=1 y=2 z=3"; my @pairs = $data =~ /(\w+)=(\d+)/g; print "@pairs\n"; # x 1 y 2 z 3 # /x modifier $text =~ m{ Perl # the word \s+ # whitespace language }x and print "Matched with /x\n";

💾 File Handling

🎯 Complete Definition

File I/O uses filehandles (bareword or lexical). open() function, modes: < read, > write, >> append, |- pipe, etc. close() flushes and closes. die on errors. Best practice: lexical filehandles, three-argument open, and error checking.

🏗️ File Operations

  • open my $fh, '<', 'file.txt' or die $!; - read mode
  • open my $fh, '>', 'out.txt'; - write mode
  • print $fh "data\n"; - write to file
  • my $line = <$fh>; - read one line
  • while (<$fh>) { ... } - read line by line
  • read, sysread, write, syswrite - low-level I/O
  • seek, tell - reposition

🔧 Special Filehandles

STDIN, STDOUT, STDERR are predefined. DATA reads after __END__ or __DATA__. Use File::Slurp or Path::Tiny for simpler operations.

# Write open my $out, '>', 'codeorbit.txt' or die "Cannot write: $!"; print $out "CodeOrbitPro Perl Master!\n"; print $out "Line 2\n"; close $out; # Read line by line open my $in, '<', 'codeorbit.txt' or die "Cannot read: $!"; while (my $line = <$in>) { chomp $line; print "Read: $line\n"; } close $in; # Slurp file open $in, '<', 'codeorbit.txt'; my $content = do { local $/; <$in> }; # undef input separator print "Full content: $content"; close $in; # Autodie use autodie; open my $fh, '>>', 'codeorbit.txt'; # dies on failure print $fh "Appended line\n";

🛡️ Error Handling

🎯 Complete Definition

Perl does not have built-in try/catch but uses eval for exception trapping. $@ contains error message. Modules like Try::Tiny, Syntax::Keyword::Try (experimental) provide structured exception handling. die throws exception, warn issues warning.

🏗️ Error Handling Methods

  • eval { ... }; - traps exceptions
  • if ($@) { ... } - check for error
  • die "error msg"; - raise exception
  • warn "warning"; - print to STDERR
  • carp, croak, confess from Carp module
  • $SIG{__DIE__} - global die hook

🔧 Modules & Modern

Use Try::Tiny for lexical exception handling. autodie for automatic error checking. Exception::Class for hierarchy.

# eval block eval { my $result = 10 / 0; # will die print "Never reached\n"; }; if ($@) { print "Caught error: $@"; } # custom die sub divide { my ($a, $b) = @_; die "Division by zero" if $b == 0; return $a / $b; } eval { divide(10, 0) }; print "Error: $@" if $@; # Try::Tiny example (if installed) use Try::Tiny; try { die "something wrong"; } catch { print "Caught: $_\n"; }; # autodie use autodie; eval { open my $fh, '<', 'nonexistent.txt'; }; print "Open failed: $@" if $@;

📦 Packages & Modules

🎯 Complete Definition

Package provides a namespace (separate symbol table). Module is a .pm file containing a package. use Module loads and imports. require loads at runtime. @INC holds search paths. %INC tracks loaded modules. CPAN modules follow standard layout.

🏗️ Module Features

  • package MyPackage; - define namespace
  • use Module qw(functions); - import
  • require Module; - runtime load
  • @EXPORT, @EXPORT_OK in Exporter module
  • our $var; - package variable
  • package version $VERSION

🔧 CPAN & Toolchain

Install with cpan Module, cpanm. Standard modules: strict, warnings, Data::Dumper, File::Spec, etc. Write modules with object-oriented or functional style.

# File: MyUtils.pm package MyUtils; use strict; use warnings; use Exporter qw(import); our @EXPORT = (); # none by default our @EXPORT_OK = qw(hello add); sub hello { return "Hello from MyUtils" } sub add { return $_[0] + $_[1] } 1; # true return # In main script use lib '.'; # add current dir to @INC use MyUtils qw(add); # import add only print add(5,3), "\n"; # 8 # built-in modules use Data::Dumper; my $ref = [1,2,{a=>1}]; print Dumper($ref);

🔗 References

🎯 Complete Definition

A reference is a scalar value pointing to another Perl variable (scalar, array, hash, subroutine, etc.). Used to create complex data structures (arrays of arrays, hashes of hashes). References are created with backslash \ or anonymous constructors [] and {}. Dereference with sigil prefix or arrow ->.

🏗️ Reference Types

  • $scalar_ref = \$var; - reference to scalar
  • $array_ref = \@arr; - reference to array
  • $hash_ref = \%hash; - reference to hash
  • $code_ref = sub { ... }; - anonymous subroutine
  • $anon_array = [1,2,3]; - anonymous array ref
  • $anon_hash = {a=>1, b=>2}; - anonymous hash ref

🔧 Dereferencing

$$scalar_ref, @$array_ref, %$hash_ref, &$code_ref() or $array_ref->[0], $hash_ref->{key}. Arrow for nested: $matrix->[1][2].

# Array reference my @arr = (10,20,30); my $arr_ref = \@arr; print $arr_ref->[1], "\n"; # 20 push @$arr_ref, 40; print "@$arr_ref\n"; # 10 20 30 40 # Anonymous array ref my $colors = ['red', 'green', 'blue']; print $colors->[0], "\n"; # red # Hash reference my $student = { name => 'CodeOrbitPro', xp => 2500, skills => ['Perl', 'Python'] }; print $student->{name}, "\n"; print $student->{skills}[1], "\n"; # Python # Nested data my $matrix = [[1,2],[3,4]]; print $matrix->[1][0], "\n"; # 3 # Subroutine reference my $square = sub { $_[0] ** 2 }; print $square->(5), "\n"; # 25

⚡ OOP & Advanced

🎯 Complete Definition

Perl's OOP is simple: a class is a package, an object is a blessed reference (using bless), methods are subroutines. Inheritance via @ISA. Method resolution: depth-first search. Multiple inheritance supported. Modern OOP can use Moo or Moose for advanced features.

🏗️ OOP Features

  • bless $ref, 'Class'; - create object
  • sub new { ... } - constructor (by convention)
  • @ISA - inheritance list
  • $obj->method(@args) - method call
  • $class->method(@args) - class method
  • AUTOLOAD - handle undefined methods

🔥 Advanced Topics

Closures (subs that capture lexical variables). Signatures (Perl 5.20+). Postderef feature. Subroutine attributes. Inline::C for XS. Coroutines with Coro module. Async with IO::Async or AnyEvent.

# Simple class package PerlPro; sub new { my ($class, %args) = @_; return bless \%args, $class; } sub gain_xp { my ($self, $points) = @_; $self->{xp} += $points; return $self->{xp}; } sub info { my $self = shift; return "$self->{name} (XP: $self->{xp})"; } package main; my $coder = PerlPro->new(name => "CodeOrbitPro", xp => 2500); print $coder->info, "\n"; $coder->gain_xp(500); print $coder->info, "\n"; # Inheritance package PerlMaster; our @ISA = qw(PerlPro); sub new { my ($class, %args) = @_; my $self = $class->SUPER::new(%args); $self->{rank} = "Master"; return $self; } my $master = PerlMaster->new(name => "Larry", xp => 9999); print $master->info, " Rank: $master->{rank}\n"; # closure sub make_counter { my $count = 0; return sub { return ++$count }; } my $c = make_counter(); print $c->(); # 1