Skip to content

cheatnotes/perl-cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Perl Programming Cheatsheet

Comprehensive reference covering syntax, variables, operators, loops, arrays, hashes, regex, file I/O, subroutines, references, modules, error handling, special vars, built-in functions, one-liners & best practices. Essential for beginners & pros.

Table of Contents

  1. Basic Syntax
  2. Data Types
  3. Variables
  4. Operators
  5. Control Structures
  6. Loops
  7. Arrays
  8. Hashes
  9. Subroutines (Functions)
  10. Regular Expressions
  11. File I/O
  12. References
  13. Packages and Modules
  14. Error Handling
  15. Special Variables
  16. Built-in Functions
  17. One-Liners
  18. Best Practices

1. Basic Syntax

# This is a comment

# Hello World
print "Hello, World!\n";

# Statements end with semicolon
$name = "John";
print "Hello $name\n";  # Variable interpolation

# Strict mode (recommended)
use strict;
use warnings;

# Enable modern syntax
use v5.36;  # Enables say, signatures, etc.
say "Modern Perl";  # say adds newline automatically

2. Data Types

Type Example Description
Scalar $num = 42; Single value (number, string, reference)
Array @arr = (1,2,3); Ordered list of scalars
Hash %hash = ('a',1,'b',2); Key-value pairs
# Scalar types
$integer = 42;
$float = 3.14;
$string = "Hello";
$string_single = 'Hello';  # No interpolation

# Numbers
$octal = 0755;     # 493 decimal
$hex = 0xFF;       # 255
$binary = 0b1010;  # 10

3. Variables

# Variable naming (sigils)
$scalar = "value";    # $ for scalar
@array = (1,2,3);     # @ for array
%hash = (a=>1,b=>2);  # % for hash

# Variable scope
my $local = "lexical";      # Lexical scope
our $global = "package";    # Package global
local $temp = $global;      # Temporary local change
state $counter = 0;         # Persistent (5.10+)

# Variable interpolation
$name = "Bob";
print "Hello $name\n";      # Hello Bob
print 'Hello $name\n';      # Hello $name\n
print "Hello ${name}ly\n";  # Hello Bobly

4. Operators

Arithmetic

+   # Addition
-   # Subtraction
*   # Multiplication
/   # Division
%   # Modulo
**  # Exponentiation
++  # Increment
--  # Decrement

Comparison

Numeric String Meaning
== eq Equal
!= ne Not equal
< lt Less than
> gt Greater than
<= le Less or equal
>= ge Greater or equal
<=> cmp Compare (returns -1,0,1)

Logical

&&  # and
||  # or
!   # not
//  # defined-or (5.10+)

String

.      # Concatenation
x      # Repetition
$str = "Hello " . "World";
$str = "Ha" x 3;  # HaHaHa

Assignment

=  +=  -=  *=  /=  %=  **=  .=  x=

5. Control Structures

# if-elsif-else
if ($x > 10) {
    print "Big";
} elsif ($x > 5) {
    print "Medium";
} else {
    print "Small";
}

# unless (opposite of if)
unless ($x == 0) {
    print "Not zero";
}

# Statement modifiers (postfix)
print "Positive" if $x > 0;
print "Empty" unless @array;

# Ternary operator
$result = $x > 0 ? "Positive" : "Non-positive";

# given/when (experimental, use Switch or match::simple)
use feature 'switch';
given ($value) {
    when (1)   { say "One" }
    when (2)   { say "Two" }
    default    { say "Other" }
}

6. Loops

# while
while ($i < 10) {
    print $i++;
}

# until
until ($i == 10) {
    print $i++;
}

# for (C-style)
for ($i = 0; $i < 10; $i++) {
    print $i;
}

# foreach (most common)
foreach $item (@array) {
    print $item;
}

# Default $_ variable
foreach (@array) {
    print $_;
}

# Loop control
last;      # Exit loop
next;      # Skip to next iteration
redo;      # Repeat current iteration

# Loop labels
OUTER: foreach $row (@matrix) {
    foreach $col (@$row) {
        next OUTER if $col < 0;
    }
}

7. Arrays

# Creation
@empty = ();
@numbers = (1, 2, 3);
@mixed = (1, "two", 3.0);
@range = (1..10);           # (1,2,3,4,5,6,7,8,9,10)
@letters = ('a'..'z');

# Access
$first = $array[0];          # Single element (uses $)
$last = $array[-1];          # Last element
$second_last = $array[-2];

# Slices
@subset = @array[0,2,4];     # Elements at indices 0,2,4 (uses @)
@range_slice = @array[2..5];

# Assignment
$array[0] = "new";
@array[1,2] = ("x", "y");

# Length
$size = scalar(@array);
$size = $#array + 1;         # $#array = last index

# Operations
push(@array, $value);        # Add to end
pop(@array);                 # Remove from end
unshift(@array, $value);     # Add to beginning
shift(@array);               # Remove from beginning

# Join and split
$string = join(", ", @array);
@parts = split(/ /, $string);

# Sorting
@sorted = sort @array;
@sorted = sort {$a <=> $b} @numbers;  # Numeric sort

# Map and grep
@sq = map {$_ * $_} @numbers;
@even = grep {$_ % 2 == 0} @numbers;

8. Hashes

# Creation
%empty = ();
%colors = ("red", "#FF0000", "green", "#00FF00");
%colors = (red => "#FF0000", green => "#00FF00");  # Fat comma

# Access
$value = $hash{$key};        # Single value (uses $)
$hash{$key} = "new value";

# Slices
@values = @hash{'key1','key2'};  # Hash slice (uses @)
@hash{'a','b'} = (1,2);

# Operations
delete $hash{$key};          # Delete key-value pair
exists $hash{$key};          # Check if key exists

# Keys and values
@keys = keys %hash;
@values = values %hash;
$count = keys %hash;         # Number of pairs

# Iteration
while (($key, $value) = each %hash) {
    print "$key => $value\n";
}

foreach $key (keys %hash) {
    print "$key => $hash{$key}\n";
}

# Merge hashes
%merged = (%hash1, %hash2);  # Later values overwrite earlier

9. Subroutines (Functions)

# Basic subroutine
sub greet {
    my $name = shift;
    return "Hello, $name";
}

# Calling
say greet("Alice");

# Parameters (using @_)
sub sum {
    my $total = 0;
    foreach my $num (@_) {
        $total += $num;
    }
    return $total;
}

# Subroutine signatures (5.20+)
use feature 'signatures';
sub multiply($x, $y) {
    return $x * $y;
}

# Prototypes (advanced, use sparingly)
sub push_array(\@@);  # Similar to built-in push

# Return value (last evaluated expression if no return)
sub add {
    $_[0] + $_[1];     # Returns automatically
}

# Context awareness
sub context_demo {
    return wantarray ? (1,2,3) : 42;  # List vs scalar context
}

# Default arguments
sub greet {
    my $name = shift // "World";
    print "Hello $name\n";
}

# Variable number of arguments
sub avg {
    return undef unless @_;
    my $sum = 0;
    $sum += $_ for @_;
    return $sum / @_;
}

10. Regular Expressions

Matching

# Basic match
if ($string =~ /pattern/) { ... }
if ($string !~ /pattern/) { ... }

# Case-insensitive
$string =~ /pattern/i;

# Global match (find all)
while ($string =~ /(pattern)/g) { ... }

# Binding operators
$string =~ s/old/new/;       # Substitute (once)
$string =~ s/old/new/g;      # Global substitute

# Using capture groups
if ($string =~ /(\d+)-(\d+)-(\d+)/) {
    $year = $1;
    $month = $2;
    $day = $3;
}

Metacharacters

Pattern Matches
. Any single character (except newline)
\d Digit [0-9]
\D Non-digit
\w Word character [a-zA-Z0-9_]
\W Non-word
\s Whitespace
\S Non-whitespace
\n Newline
\t Tab

Quantifiers

Quantifier Meaning
* 0 or more
+ 1 or more
? 0 or 1
{3} Exactly 3
{2,5} 2 to 5
{3,} 3 or more

Anchors

Anchor Matches
^ Start of string
$ End of string
\b Word boundary
\B Non-word boundary

Character Classes

[aeiou]     # Any vowel
[^aeiou]    # Any consonant
[a-z]       # Any lowercase letter
[0-9A-F]    # Hex digit

Modifiers

/pattern/i   # Case insensitive
/pattern/g   # Global
/pattern/m   # Multi-line
/pattern/s   # Single line (dot matches \n)
/pattern/x   # Extended (allow whitespace and comments)

Examples

# Email validation
$email =~ /^[\w.-]+@[\w.-]+\.[a-z]{2,}$/i;

# Split with regex
@parts = split(/\s+/, $string);  # Split on whitespace

# Extract all numbers
@numbers = $string =~ /\d+/g;

# Substitution with evaluation
$string =~ s/(\d+)/$1 * 2/ge;   # Double all numbers

11. File I/O

# Opening files
open(my $fh, '<', 'input.txt') or die "Cannot open: $!";
open(my $out, '>', 'output.txt') or die "Cannot open: $!";
open(my $log, '>>', 'debug.log') or die "Cannot open: $!";

# Reading
while (my $line = <$fh>) {
    chomp $line;  # Remove newline
    print $line;
}

# Using $_ (default variable)
while (<$fh>) {
    chomp;
    print $_;
}

# Reading entire file
my @lines = <$fh>;
my $content = do { local $/; <$fh> };  # Slurp mode

# Writing
print $out "Hello\n";   # Using filehandle
say $out "Hello";       # With newline (5.10+)

# File tests
if (-e "file.txt") { print "Exists\n"; }
if (-f "file.txt") { print "Regular file\n"; }
if (-d "dir") { print "Directory\n"; }
if (-r "file.txt") { print "Readable\n"; }
if (-w "file.txt") { print "Writable\n"; }
if (-x "file") { print "Executable\n"; }
if (-z "file.txt") { print "Empty\n"; }
if (-s "file.txt") { print "Size: " . (-s "file.txt") . "\n"; }
if (-T "file.txt") { print "Text file\n"; }
if (-B "file.txt") { print "Binary file\n"; }

# File operations
rename("old.txt", "new.txt") or die "Rename failed: $!";
unlink("file.txt") or die "Delete failed: $!";
mkdir("newdir", 0755) or die "Mkdir failed: $!";
rmdir("emptydir") or die "Rmdir failed: $!";

# Filehandles (autoclose at scope end)
open(my $fh, '<', 'file.txt') or die "Cannot open: $!";
# ... use $fh ...
# File automatically closes when $fh goes out of scope

# STDIN/STDOUT/STDERR
$line = <STDIN>;
print STDOUT "Output\n";
print STDERR "Error message\n";

# Using File::Slurp (CPAN)
use File::Slurp qw(read_file write_file);
my $text = read_file('file.txt');
write_file('output.txt', $text);

12. References

# Creating references
$scalar_ref = \$scalar;
$array_ref = \@array;
$hash_ref = \%hash;
$sub_ref = \&subroutine;

# Anonymous references
$array_ref = [1, 2, 3];
$hash_ref = {a => 1, b => 2};
$code_ref = sub { return "Hello" };

# Dereferencing
$$scalar_ref = 42;                     # Scalar
my @arr = @$array_ref;                 # Array
my %hash = %$hash_ref;                 # Hash
&$code_ref();                          # Subroutine

# Arrow operator (preferred)
$array_ref->[0] = 10;
$hash_ref->{key} = "value";

# Nested structures
$complex = [
    {name => "Alice", age => 30},
    {name => "Bob", age => 25}
];
print $complex->[0]->{name};  # Alice
print $complex->[0]{name};    # Arrow optional between []

# Multidimensional arrays (using references)
my @matrix = (
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
);
$value = $matrix[1]->[2];  # 6

# Autovivification
my $ref;                    # undef
$ref->{key}->[0] = 42;      # Creates structures automatically

# Reference checking
if (ref($ref) eq "ARRAY") { print "Array reference\n"; }
if (ref($ref) eq "HASH") { print "Hash reference\n"; }
if (ref($ref) eq "CODE") { print "Code reference\n"; }
if (ref($ref) eq "SCALAR") { print "Scalar reference\n"; }

# Circular references (avoid memory leaks)
use Scalar::Util qw(weaken);
weaken($node->{parent});    # Weak reference

13. Packages and Modules

# Defining a package
package MyModule;
use strict;
use warnings;

our $VERSION = "1.0";

sub new {
    my $class = shift;
    my $self = { @_ };
    return bless $self, $class;
}

sub method {
    my $self = shift;
    return $self->{data};
}

1;  # Must return true

# Using modules
use MyModule;                    # Load at compile time
require MyModule;                # Load at runtime

use MyModule qw(function1 function2);  # Import specific functions
use MyModule ();                 # Load but don't import

# Object-oriented usage
my $obj = MyModule->new(data => "value");
print $obj->method();

# Exporter (for function export)
package MyUtils;
use parent 'Exporter';
our @EXPORT = qw(util1 util2);          # Auto-export
our @EXPORT_OK = qw(util3 util4);       # Optional export
our %EXPORT_TAGS = (all => [@EXPORT, @EXPORT_OK]);

sub util1 { ... }
sub util2 { ... }

1;

# Using Exporter
use MyUtils;                    # Gets util1, util2
use MyUtils qw(util3);          # Gets only util3
use MyUtils qw(:all);           # Gets everything

# Namespace manipulation
package main;                   # Back to main namespace
$MyModule::variable = 42;       # Package variable access

# Perl modules naming convention
# Core: File::Basename, Getopt::Long
# CPAN: JSON, DBI, Moose
# Local: lib/My/Module.pm = My::Module

# Best practices
use strict;
use warnings;
use v5.36;  # or higher

14. Error Handling

# die - terminate with error
die "Something went wrong\n";
die "Error: $!";               # Include system error

# warn - print warning (non-fatal)
warn "Warning: File not found\n";

# eval - trap exceptions
eval {
    open(my $fh, '<', 'missing.txt') or die "Cannot open: $!";
    # ... more code ...
};

if ($@) {  # Error caught
    print "Caught error: $@\n";
}

# $@ contains the error from last eval

# autodie (recommended)
use autodie;
open(my $fh, '<', 'missing.txt');  # Dies automatically

# Try::Tiny (CPAN)
use Try::Tiny;
try {
    die "error";
} catch {
    warn "Caught: $_";
};

# Carp module (better stack traces)
use Carp;
carp "Warning (caller's perspective)";
cluck "Full stack trace warning";
croak "Error (reported at caller's line)";
confess "Error with full stack trace";

# Fatal warnings (5.10+)
use warnings FATAL => 'all';

# Custom exceptions
package MyException;
use overload '""' => sub { shift->{message} };

sub throw {
    my ($class, $message) = @_;
    die bless { message => $message }, $class;
}

# Using custom exception
eval {
    MyException->throw("Custom error");
};
if (blessed($@) && $@->isa('MyException')) {
    print "Caught custom: $@\n";
}

15. Special Variables

$_              # Default variable (most used)
@_              # Subroutine arguments
$!              # System error message / errno
$@              # Error from last eval
$$              # Process ID
$0              # Program name
$^O             # Operating system name
$^T             # Script start time (epoch)
$|              # Autoflush (1=enabled, 0=disabled)
$.              # Current line number for last filehandle read
$"              # List separator (used in interpolation)
$,              # Output field separator for print
$\              # Output record separator (added after print)
$/              # Input record separator (default newline)

@ARGV           # Command line arguments
@INC            # List of include directories
%ENV            # Environment variables
%SIG            # Signal handlers

# Some examples
local $| = 1;   # Disable buffering
local $/ = undef; # Slurp mode (read whole file)
local $" = ", ";   # @array interpolation: "1, 2, 3"

$SIG{INT} = sub { die "Interrupted\n" };  # Ctrl-C handler

16. Built-in Functions

Scalar functions

chomp($var);        # Remove trailing newline
length($str);       # String length
lc($str);           # Lowercase
uc($str);           # Uppercase
lcfirst($str);      # First char lowercase
ucfirst($str);      # First char uppercase
index($str, $sub);  # Find substring position
rindex($str, $sub); # Find last position
substr($str, $off, $len); # Extract substring
reverse($str);      # Reverse string
int($num);          # Integer part
abs($num);          # Absolute value
rand($max);         # Random number [0, max)
srand($seed);       # Seed random generator
defined($var);      # Check if defined
undef($var);        # Undefine variable
hex($str);          # Hex to decimal
oct($str);          # Octal to decimal
chr($num);          # Number to character
ord($char);         # Character to number

Array functions

push(@arr, @vals);
pop(@arr);
shift(@arr);
unshift(@arr, @vals);
splice(@arr, $offset, $len, @replacement);
sort(@arr);
reverse(@arr);
grep { condition } @arr;
map { transformation } @arr;
join($sep, @arr);
scalar(@arr);       # Force scalar context
wantarray();        # Detect calling context

Hash functions

keys(%hash);
values(%hash);
each(%hash);
delete($hash{$key});
exists($hash{$key});

File functions

open($fh, $mode, $filename);
close($fh);
binmode($fh);
read($fh, $buffer, $bytes);
seek($fh, $pos, $whence);
tell($fh);
eof($fh);
stat($filename);
lstat($filename);
opendir($dh, $dir);
readdir($dh);
closedir($dh);
mkdir($dir, $mode);
rmdir($dir);
unlink(@files);
rename($old, $new);
chmod($mode, @files);
chown($uid, $gid, @files);
symlink($target, $link);
readlink($link);

Time functions

time();             # Current epoch seconds
localtime();        # Local time (list/string)
gmtime();           # GMT time
sleep($seconds);
usleep($microseconds);

Other utilities

eval($string);      # Run Perl code
do($file);          # Execute Perl file
system(@cmd);       # Run shell command
exec(@cmd);         # Replace process
qx/ls -l/;          # Backticks - capture output
`ls -l`;            # Same as above

17. One-Liners

# Common perl one-liners (run from command line)

# Replace text in file (in-place)
perl -pi -e 's/old/new/g' file.txt

# Print lines matching pattern
perl -ne 'print if /pattern/' file.txt

# Print lines NOT matching pattern
perl -ne 'print unless /pattern/' file.txt

# Print line numbers
perl -ne 'print "$.: $_"' file.txt

# Print first 10 lines (head)
perl -pe 'exit if $. > 10' file.txt

# Print last 10 lines (tail)
perl -e '@lines=<STDIN>; print @lines[-10..-1]'

# CSV manipulation
perl -F, -lane 'print $F[0]' data.csv  # Print first column

# Calculate sum of numbers
perl -lne '$sum += $_; END { print $sum }' numbers.txt

# Find duplicate lines
perl -ne 'print if $seen{$_}++' file.txt

# Extract email addresses
perl -nle 'print $1 while /([\w.-]+@[\w.-]+\.[a-z]{2,})/gi' file.txt

# Web server (simple)
perl -MHTTP::Server::Simple -e 'package My; @ISA = qw(HTTP::Server::Simple); sub handle_request { print "HTTP/1.0 200 OK\n\nHello"; } My->new(8080)->run'

# Command line switches
# -e    Execute code
# -p    Print after processing (creates while + print)
# -n    Loop but no automatic print
# -i    In-place edit (backup with .bak)
# -l    Auto-chomp and add newline
# -a    Auto-split into @F
# -F    Field separator (with -a)
# -M    Load module
# -I    Add directory to @INC

18. Best Practices

Always use

use strict;
use warnings;
use v5.16;  # or later for modern features

Naming conventions

$scalar_var      # snake_case for variables
@array_of_names
%hash_of_stuff
$CamelCase       # Package names
snake_case       # Subroutines
$ALL_CAPS        # Constants
$_               # Only as default, avoid in long blocks

Code organization

#!/usr/bin/perl
use strict;
use warnings;
use v5.36;

# Pragmas and use statements
use Carp;
use autodie;

# Constants
use constant MAX_SIZE => 1024;

# Subroutine declarations (optional)
sub process_data;

# Main code
sub main {
    my @args = @_;
    # ... code ...
    
    return 0;  # Exit code
}

exit(main(@ARGV));

# Subroutine definitions
sub process_data {
    my ($data) = @_;
    # ... code ...
}

Performance tips

# Use local references for speed
my $ref = $array[$i];
for (my $i = 0; $i < @array; $i++) {
    my $item = $ref->[$i];  # Faster
}

# Pre-extract array size
my $size = @array;
for (my $i = 0; $i < $size; $i++) { }

# Avoid creating unnecessary temporary arrays
while (my ($k,$v) = each %hash) { }  # Better than keys

# Use grep/map instead of explicit loops when possible
my @positive = grep { $_ > 0 } @numbers;

# Precompile regexes
my $regex = qr/pattern/;
$string =~ $regex;

# Use single quotes when no interpolation needed
print '$var: ';  # Faster for literal strings

# Open filehandles with local
open(my $fh, '<', $file) or die;

# Use file test operators efficiently
if (-r $file and -w $file) { }

Debugging

# Data::Dumper
use Data::Dumper;
print Dumper($complex_structure);

# Carp::Always
use Carp::Always;  # Adds stack traces to all warnings/dies

# Debug module
perl -d script.pl

# Smart::Comments (CPAN)
use Smart::Comments;
### $var  # Shows value when script runs

# Use say instead of print (when possible)
use v5.10;
say $var;  # Adds newline

# Profiling
perl -d:DProf script.pl
dprofpp  # Analyze output

# Perl::Critic (code quality)
perlcritic --brutal script.pl

Common pitfalls

# Don't: Using $a/$b for non-sort (they're special)
$c = $a + $b;  # OK
# Do: use other names

# Don't: Forgetting to chomp
$input = <STDIN>;        # Has newline
chomp($input);           # Remove newline

# Don't: Using == for strings
if ($str == "hello")     # Wrong: numeric comparison

# Don't: Overwriting $_ in nested loops
foreach (@outer) {
    foreach (@inner) {   # $_ overwritten
        print $_;
    }
}
# Use named variables instead

# Don't: Relying on boolean conversion
if ($value) { }  # Does NOT work: undef, 0, "0", "" are false

# Do: Explicit checks
if (defined $value) { }
if ($value eq "0") { }

CPAN modules worth knowing

# Must-have modules
use Modern::Perl;       # strict, warnings, features
use Path::Tiny;         # File handling
use JSON;               # JSON encode/decode
use DBI;                # Database interface
use Moose;              # Object system
use Try::Tiny;          # Exception handling

# Testing
use Test::More;
use Test::Exception;

# Web
use Mojolicious;        # Web framework
use Dancer2;            # Lightweight web framework

# Data processing
use Text::CSV;          # CSV parsing
use XML::LibXML;        # XML processing
use DateTime;           # Date/time handling

# System
use File::Find;         # File tree traversal
use Getopt::Long;       # Command line options
use Pod::Usage;         # Documentation

# Quick reference - most useful commands

# Run script
perl script.pl

# Syntax check
perl -c script.pl

# Automatic debugger
perl -d script.pl

# Strip comments
perl -p -i.bak -e 's/^\s*#.*//' script.pl

# As awk replacement
perl -lane 'print $F[1]' data.txt

# As sed replacement
perl -pi -e 's/foo/bar/g' *.txt

# One-liner template
perl -p -i -e 'code_here' filename

About

Comprehensive reference covering syntax, variables, operators, loops, arrays, hashes, regex, file I/O, subroutines, references, modules, error handling, special vars, built-in functions, one-liners & best practices. Essential for beginners & pros.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Generated from cheatnotes/cheatnotes