🐪 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.
📊 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).
🔢 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.
🔀 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.
🔄 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; }
⚙️ 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:
wantarrayto 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.
📋 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.
🔑 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.
📝 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.
💾 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.
🛡️ 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.
📦 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.
🔗 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].
⚡ 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.