Perl Cheatsheet โ Concise Reference
A cheatsheet for Perl 5.38 syntax, regular expressions, references, and the most common built-in functions โ covering ~80% of daily use cases.
Perl Perl 5.38
perl 5 (interpreter) ยท Multi-paradigm (procedural ยท OO ยท functional) ยท Dynamic
Recommended Learning Path
Start with running `perl hello.pl` and `use strict`/`use warnings` โ master scalars, arrays, hashes, and control flow โ dive into subroutines and context โ build complex data structures with references โ process text with regex โ understand `eval` error handling and `bless`-based OO โ then learn threads, networks, time, and CPAN modules as needed. The FAQ section is great for revisiting and avoiding pitfalls.
1.Hello World and Build Environment
Run Perl scripts, use strict/warnings, and command-line tools.
Minimal Program
Save as hello.pl, run with perl hello.pl. use strict and use warnings are standard.
Run and Interpret
perl directly interprets and executes scripts; -c only does syntax check, -e executes single-line code.
Shebang and Arguments
#!/usr/bin/perl declares the interpreter; command-line arguments are in @ARGV, $0 is the script name.
Output and Formatting
print does not add newline, say adds newline automatically; printf formats, sprintf returns string.
Reading Input
<STDIN> reads one line (including newline); chomp removes trailing newline; EOF returns undef.
Quote Operators
q() single-quote semantics, qq() double-quote semantics, qw() word list, qx() command substitution.
use strict/warnings
use strict forces variable declarations and disallows barewords; use warnings enables runtime warnings. Standard in modern Perl.
perldoc Documentation
perldoc comes with Perl; look up functions, modules, built-in variables, and language tutorials.
2.Variables and Constants
Scalar/array/hash declarations, my/our/local/state, and constant definitions.
Variable Declarations
Three sigils identify three containers: $ scalar, @ array, % hash. my declares lexical variables.
Scalar Type
A scalar holds one value: number, string, or reference. Strings and numbers convert automatically.
Array Operations
Arrays are lists of elements. push/pop operate on the end, shift/unshift on the beginning; indices start at 0.
Hash Operations
Hashes are key-value pairs with string keys. Iterate with keys/values/each, manage with exists/delete.
Constant Definitions
use constant defines compile-time constants with no sigil, called like subroutines.
Scope
my lexical variables are visible within the block; our declares package (global) variables; local temporarily overrides globals; state provides static lexical variables.
Default Variables
$_ is the default input variable, @_ is the argument list; common special variables include $! for system errors and $0 for the script name.
String Interpolation
In double quotes, $scalar and @array are interpolated; single quotes output literally; curly braces delimit variable names.
3.Data Types
Scalars, undef, truthiness, lists and hashes, file handles, and typeglobs.
Scalar Type
Scalar is the only basic type; it can hold integers, floats, strings, or references. No explicit type declaration needed.
Number/String Conversion
Automatic conversion based on context: + for numeric, . for concatenation. Explicit conversion uses +0 and ."".
undef and defined
undef means undefined; in numeric context it is 0, in string context empty string. Use defined to test.
Truthiness
Only undef, 0, "0", and empty string are false; everything else is true. Logical operators return operands.
Arrays and Lists
List literals (1,2,3), qw word lists, range 1..5. Context determines whether the whole list or individual elements are used.
Hash Key-Value Pairs
The fat arrow => auto-quotes the left side; keys and values appear in pairs; keys are strings or integers.
File Handles
STDIN/STDOUT/STDERR are built-in handles; open lexical filehandles to read/write files; the three-argument form is safest.
Typeglob
The * prefix denotes a symbol table entry; used to alias scalars/arrays/subroutines. Less common in modern code.
4.References and Dereferencing
Perl uses references instead of pointers: backslash to take address, dereferencing, arrow operator, and nested structures.
Reference Basics
Backslash \ takes a reference to a variable, producing a scalar of reference type; the ref function returns the type name.
Dereferencing
@$ref, %$ref, $$ref restore a reference to its original type; the brace form ${$ref} is more visible.
Arrow Operator
-> dereferences nested structures: $ref->[0] and $ref->{key}, chained layer by layer.
Anonymous References
[] anonymous array, {} anonymous hash, sub {} anonymous function; construct directly without named variables.
Nested Structures
Composite structures like array of hashes, hash of arrays; dereference layer by layer when iterating.
Reference Parameters
Passing references avoids copying large arrays and lets you modify caller's data in place; returning references is more efficient.
bless and Objects
bless tags a reference with a class name to make it an object; ref then returns the class name. An object is essentially a reference.
Reference Comparison
Compare references by address with ==; ref returns the type; reference counting manages lifetime.
5.Control Flow
if/unless, postfix form, for/foreach/while, and next/last/redo.
if/elsif/else
if tests truthiness; elsif chains; unless is the reverse. Parentheses around conditions are not required.
unless and until
unless is the negation of if, until is the negation of while; do-until executes at least once.
Postfix Control
if/unless/for/while can follow a single statement โ Perl idiomatic style. Only modifies one statement.
for/foreach Loop
for can be written C-style or iterate lists; foreach is an alias. Without a variable, $_ is used.
while Loop
while loops while condition is true; reading files line by line with while is most idiomatic; do-while executes once first.
next/last/redo
next skips current iteration, last exits loop, redo repeats current iteration; labels control nested loops.
Ternary and Short-Circuit
?: conditional expression; || and // provide defaults; logical operators return operands.
goto and Labels
goto can jump to labels (limited form); prefer labelled last for multi-level exits. goto is rarely used in everyday code.
6.Functions and Subroutines
sub definitions, @_ arguments, return values, closures, prototypes, and signatures.
Function Definition
sub defines a named subroutine; the last expression is returned automatically. Use parentheses to pass arguments.
@_ and Arguments
Arguments are in @_; shift takes the first; @_ elements are aliases โ modifying in place propagates back.
Return Values
Return scalar or list depending on context; wantarray detects caller context; return references to avoid copying.
Anonymous Subroutine
sub {} creates a function reference, called via ->(); can be used as callback, stored in array or hash.
Closures
Closures capture lexical variables and remember state; each call to the factory creates an independent copy.
Prototypes
Prototypes constrain argument context at compile time, e.g. (\@) forces an array reference. Modern code prefers signatures.
Function Signatures
feature 'signatures' provides declarative parameters (stable in 5.36+); supports defaults and array parameters.
Function References
\&sub takes a function reference; call via ->() or &$ref(); used for callbacks, dispatch tables, and higher-order functions.
7.Strings
Quotes, interpolation, concatenation, formatting, substrings, and encoding.
String Literals
Single quotes literal, double quotes interpolate; q()/qq() are equivalent; adjacent strings concatenate automatically.
Interpolation Rules
In double quotes, $scalar and @array interpolate; curly braces delimit names; indices/dereferences also interpolate.
Concatenation and Repetition
. concatenates strings, x repeats, join joins arrays; length gives length, reverse reverses.
Substrings and Search
substr gets/replaces substrings; index/rindex find positions (returns -1 if not found).
chomp and split
chomp removes trailing newline; split divides by delimiter into a list; join is the inverse.
printf/sprintf
printf outputs directly, sprintf returns a string; %d/%s/%f formatters with zero-padding and alignment.
Case and Trimming
uc/lc/ucfirst change case; use substitution regex to strip whitespace; tr/// is character translation.
Encoding and UTF-8
use utf8 marks source as UTF-8; encode/decode transcoding; read/write files with encoding layers.
8.Collections and Data Structures
Array/hash operations, slices, map/grep, sorting, and List::Util.
Array Add/Remove/Modify
push/pop/shift/unshift for the four ends; splice for mid-array insert/delete; reverse/sort.
Slices
@arr[...] takes an array slice, %hash{...} takes a hash slice; slices can be assigned as a whole.
List Operations
sum/min/max come from List::Util; grep for deduplication, range extraction, list destructuring.
map and grep
grep filters, map transforms; both iterate with $_. grep in scalar context returns the count.
Hash Iteration
keys/values return key/value lists; each iterates key-value pairs; exists/delete manage keys.
Hash Idioms
Hashes for counting, deduplication, sets, caching, and grouping. Be careful with add/delete during iteration.
Sorting
sort defaults to string order; use a custom comparison block with <=> for numeric, cmp for string.
List::Util
sum/sum0/min/max/first/reduce/any/all/shuffle. sum0 returns 0 for an empty list.
9.Memory and Performance
Reference counting, circular references, weak references, autovivification, and performance benchmarking.
Reference Counting
Perl uses reference counting for automatic memory reclamation; no manual free needed. Released when the count reaches zero.
Circular References
Mutual references keep the count non-zero and cause leaks; use weak references or manually break cycles.
Weak References
Scalar::Util::weaken makes a reference not increase the count; once the target is freed, the weak reference becomes undef.
Scope-Based Release
Lexical variables and handles are automatically released/closed when out of scope; undef releases earlier.
Autovivification
Assigning to an undefined reference auto-creates containers; convenient for writes, may mistakenly create when reading nested.
Allocation and Speedups
Preallocate arrays, precompile regex, prefer join over interpolation; profile before optimizing.
Memory Measurement
Devel::Size measures structure sizes; observe peak memory; stream large files.
Performance Benchmark
Benchmark module compares implementations; Time::HiRes provides high-resolution timing.
10.Object-Oriented Programming
Bless references, methods, inheritance, accessors, operator overloading, and Moose/Moo.
bless Construction
bless tags a reference with a class name to make it an object; an object is essentially a reference with a class name.
Methods and Invocation
Left side of -> is the object, right side is the method; the first argument to the method is $self.
Inheritance
use parent declares the parent class; subclass overrides methods of the same name; parent methods are reusable.
Constructors
new receives class name and arguments, returns a blessed object; multiple constructors can be provided.
Encapsulation and Accessors
Encapsulate field access as methods; write accessors can validate; prevents external direct field modification.
Operator Overloading
use overload defines +, "" etc.; lets objects participate in numeric/string operations.
Moo/Moose
Moo is a lightweight object system: has declares attributes, auto-generates accessors, extends inherits.
Roles and Composition
Moo::Role defines reusable method sets, included with `with`; composition over inheritance.
11.Error Handling
die/warn, eval catching, Try::Tiny, Carp, and custom exceptions.
die and warn
warn prints a warning without exiting; die prints and terminates; die can throw a string or object.
eval Catching
eval BLOCK catches exceptions; sets $@ on failure; returns the last expression of the block on success.
$@ Handling
$@ holds the most recent error; match on string or check object type; distinguish undef from exception.
Try::Tiny
try/catch/finally structure is clear; $_ carries the error; solves the $@ race condition.
Carp Errors
croak/carp report the caller's location; confess/cluck include a stack trace. Friendlier for library code.
Custom Exceptions
die objects and check with ref/isa; overload "" for friendly stringification.
autodie
autodie makes open and other syscalls die on failure, eliminating the need for `or die`.
Error Handling Patterns
`or die` idiom, early validation, fail-fast return; top-level die, internal library returns.
12.File I/O
open read/write, diamond operator, slurp, encoding, paths, and JSON.
Open and Read
Three-argument open to read files; line-by-line while is most memory-efficient; -e/-f check file attributes.
Write and Append
> for overwrite, >> for append; print/printf to write handles; umask controls permissions.
Diamond Operator
<> reads from argument files, or STDIN if none; $. is the cumulative line number, $ARGV is the current file name.
Read Entire File
local $/ set to undef to read all at once; File::Slurper provides the read_text convenience function.
binmode and Encoding
binmode for binary safety; <:utf8 layer for UTF-8 reading/writing; :raw removes the encoding layer.
Standard Handles
STDIN/STDOUT/STDERR; duplicate handles, detect terminal, immediate flush.
Path Operations
Cwd for current directory, File::Spec for cross-platform path joining, glob for file matching, File::Find for recursion.
JSON Processing
JSON::PP is a core module: encode/decode, pretty, UTF-8. JSON::XS for production performance.
13.Common Pitfalls
The most common pitfalls in Perl daily development and the correct way to write them.
Forgetting use strict
Without strict, typos are silent and variables auto-globalize. strict is the safety baseline.
Context Confusion
Scalar and list contexts differ: array in scalar context is its length. Use scalar explicitly.
Forgetting chomp
<STDIN> includes the newline; forgetting chomp makes string comparisons always fail.
Mixed Comparison Operators
== for numeric comparison, eq for string comparison. Mixing them wrongly treats "10" and "010" as equal.
Unordered Hash Iteration
Hash internal order is undefined; relying on iteration order causes random bugs. Sort keys if order is needed.
Reading Triggers Autovivification
Reading nested structures auto-creates intermediate references, silently growing memory. Short-circuit checks prevent this.
Confusing local and my
local temporarily overrides globals (restored after block); my is the lexical local variable.
Outdated open Syntax
Two-argument open + bareword handle pollutes the symbol table and is unsafe. Use three-argument + lexical handle.
Array in Scalar Context
Array in scalar context returns length, list returns last element. Use scalar to get length.
14.Multithreading
threads create threads, threads::shared shared data, locks, and queue synchronization.
Create Threads
threads->create starts a new thread; join waits for it to finish and returns the result.
join and Errors
join returns the thread's result; die inside the thread propagates to the main thread and can be caught with eval.
Shared Data
threads::shared :shared variables are shared across threads; regular my variables are per-thread copies.
Locks and Semaphores
lock protects critical sections; Thread::Semaphore throttles. Locks auto-release at scope end.
Thread Queue
Thread::Queue is a thread-safe queue; dequeue blocks when empty; ideal for producer-consumer.
Thread Arguments
Second argument and beyond of create are passed to the subroutine; lexical variables are per-thread copies.
Parallel Tasks
Fixed thread pool picks up tasks; atomically allocate a shared index, avoiding per-task thread creation.
Thread Pool Pattern
Queue dispatch + result queue collection; call end multiple times to wake all blocked threads.
15.Network Programming
TCP sockets, HTTP clients, URL parsing, and DNS queries.
TCP Client
IO::Socket::INET creates a connection; print to send, <...> to read the response.
TCP Server
Listen on a port, accept connections; each connection can be echoed or handled by a child process.
HTTP GET
HTTP::Tiny is a core module; get returns status/content, can be paired with JSON::PP for parsing.
HTTP POST
post sends arbitrary body; post_form URL-encodes and submits forms automatically.
URL Parsing
URI module parses and builds URLs; query_form reads/writes query parameters with auto-encoding.
DNS Query
Net::DNS resolves A/MX/TXT records; search returns a response object; requires external module.
Socket Options
setsockopt sets low-level options; timeout controls blocking; IO::Select provides non-blocking waits.
REST Client
Wrap HTTP::Tiny for unified auth and JSON handling; errors thrown uniformly to caller.
16.Date and Time
time/localtime, strftime formatting, Time::Piece, and DateTime handling.
localtime Decomposition
time returns epoch; localtime decomposes into year/month/day/hour/min/sec; note month and year offsets.
strftime Formatting
POSIX::strftime uses %Y %m %d placeholders; %A %B output weekday and month names.
Timestamp Conversion
timelocal/timegm convert local/UTC time arrays back to epoch; note the offsets.
sleep Delay
sleep integer seconds; Time::HiRes supports fractional and microsecond delays; select for non-blocking waits.
Elapsed Time Measurement
time for second-level timing; Time::HiRes for millisecond; DateTime for cross-time-zone/date differences.
DateTime Object
DateTime for full time handling: construction, accessors, time zone conversion, and date arithmetic.
String Parsing
Time::Piece::strptime parses date strings by format, returning epoch and differences.
Format Object
DateTime::Format::Strptime unifies parsing and formatting; RFC3339 handles ISO times.
17.Processes and Commands
system/backticks for executing commands, environment variables, @ARGV, signals, and pipes.
Execute Commands
Backticks capture output; system executes without capturing; list form avoids shell injection.
exec and system
exec replaces the current process; system waits for the child to finish; $? holds the exit status.
Environment Variables
%ENV hash reads/writes environment variables, affecting child processes; local provides temporary isolation.
Command-Line Arguments
@ARGV is the argument list; complex argument parsing uses Getopt::Long declaratively.
Exit Status
exit N sets the exit code; 0 is success, non-zero is failure; END blocks run before exit.
Signal Handling
$SIG{INT} catches signals; handlers should only set flags, with the main loop responding.
Process Pipes
-| reads child stdout, |- writes to child stdin; bidirectional interaction uses IPC::Open3.
Capture Output
Redirect to merge stdout/stderr; check $? for exit code; Capture::Tiny for structured capture.
18.Regular Expressions
Pattern matching, character classes, quantifiers, capture groups, precompilation, and substitution.
Match Basics
=~ matches, !~ non-matches; anchors ^ $ \b position; i modifier ignores case.
Match and Extract
g for global match; list context returns all matches; combine with grep for filtering arrays.
Character Classes
\d \w \s and their negations; custom [...] and negated [^...] character classes; quantifiers.
Quantifiers and Backtracking
Greedy by default, non-greedy with ?; possessive quantifier + disables backtracking; nested quantifiers risk catastrophic backtracking.
Capture Groups
$1 $2 take captures in left-parenthesis order; (?:) non-capturing; (?<name>) named capture.
Named Captures
(?<name>...) named group + %+ hash access; \k<name> backreference.
Precompiled Regex
qr// compiles once and reuses; share inside modules for better performance in large loops; modifiers allowed.
Substitution and Translation
s/// substitution, g for global, i for case-insensitive; $1 etc. in replacement; tr/// for character translation.
19.Modules and Engineering
Module structure, use/require, option parsing, CPAN installation, and testing.
Module Structure
Package name corresponds to file path; Exporter for exports; trailing 1; makes `use` succeed.
use and require
use loads and imports at compile time; require loads at runtime; do executes a file without a symbol table.
Module Installation
cpanm installs CPAN modules; core modules ship with Perl; cpanfile records dependencies.
Getopt::Long
Declarative option parsing: =s string, =i integer, flags, aliases, and negations.
Common CPAN Modules
Ecosystem like DateTime/Moose/DBI; search via MetaCPAN; use eval to probe availability.
Script and Command Line
shebang specifies interpreter; common Perl command-line options: -w, -e, -ne.
Packaging and Directory
lib/t directory layout, Makefile.PL build; -Ilib for local development loading.
Test::More
plan declares test counts; is/ok/like assertions; prove -l runs tests in batch.
About this Cheatsheet
This page is a self-contained Perl 5.38 cheatsheet, covering the language core and the most common built-in functions and a few CPAN modules โ roughly 80% of typical project usage. The content favors modern idioms: `use strict` + `use warnings` as default, postfix control flow, scalar vs list context, references for complex data structures, `say` / `state` / `signatures`. Perl is a multi-paradigm dynamic language first released by Larry Wall in 1987, famous for TMTOWTDI ("There's More Than One Way To Do It"), with deep roots in text processing, system administration, and web backends. Authoritative references include the `perldoc` shipped with Perl and the official [Perl documentation](https://perldoc.perl.org/). The 19 sections each focus on one topic โ from your first program to references, bless-based OO, and common pitfalls. Each section is split into 8โ14 sub-topics (each 5โ20 lines), giving ~150 topics in total. Code snippets are intentionally short and self-explanatory; you can copy and run them directly with `perl`. All processing happens entirely in your browser โ no uploads, no tracking. This page is part of GuruToolkit's free developer tool collection; the code snippets are free to use with no warranty.
Version 2.1.0