Perl Cheat Sheet

Last Updated: November 21, 2025

🐪 Perl

Practical Extraction and Reporting Language

Language Scripting

Basics

#!/usr/bin/perl Shebang line for executable scripts
use strict; Enforce good programming practices
use warnings; Enable helpful warning messages
print "Hello\n"; Print to STDOUT with newline
say "Hello"; Print with automatic newline (Perl 5.10+)
# Comment Single-line comment
perl script.pl Run Perl script
perl -e 'print "code"' Execute one-liner

Variables

$scalar Single value (string, number, reference)
@array Ordered list of scalars
%hash Key-value pairs
my $var = 42; Lexically scoped variable
our $var; Package-scoped variable
local $var; Temporarily modify global variable
$_ Default variable (implicit)

Arrays

@arr = (1, 2, 3); Create array
$arr[0] Access element (note $ for single value)
$#arr Last index of array
scalar @arr Array length/size
push @arr, $val; Append to end
pop @arr; Remove from end
unshift @arr, $val; Add to beginning
shift @arr; Remove from beginning
@sorted = sort @arr; Sort array
@reversed = reverse @arr; Reverse array
join ',', @arr; Join array into string
split /,/, $str; Split string into array

Hashes

%hash = (key => 'val'); Create hash
$hash{key} Access value
$hash{newkey} = 'val'; Add/modify key-value pair
delete $hash{key}; Remove key
exists $hash{key} Check if key exists
keys %hash Get all keys
values %hash Get all values
each %hash Iterate key-value pairs

Control Structures

if ($x > 5) { } If statement
elsif ($x == 5) { } Else if (note: elsif, not elseif)
else { } Else clause
unless ($x) { } If not (opposite of if)
$x = 5 if $y; Statement modifier (postfix if)
while ($x > 0) { } While loop
until ($x == 0) { } Until loop (opposite of while)
for (1..10) { } For loop with range
foreach my $i (@arr) { } Foreach loop
last; Exit loop (like break)
next; Skip to next iteration (like continue)
redo; Restart current iteration

Regular Expressions

/pattern/ Match operator
$str =~ /pattern/ Bind operator (match against $str)
$str !~ /pattern/ Negated match
s/old/new/ Substitution (replace first match)
s/old/new/g Global substitution (replace all)
s/old/new/i Case-insensitive substitution
m/pattern/ Explicit match (same as /pattern/)
($1, $2, $3) Capture groups
(?:...) Non-capturing group
\d \w \s Digit, word char, whitespace
^ $ Start and end of string
* + ? Zero or more, one or more, zero or one

File I/O

open my $fh, '<', 'file.txt'; Open file for reading
open my $fh, '>', 'file.txt'; Open file for writing (truncate)
open my $fh, '>>', 'file.txt'; Open file for appending
close $fh; Close filehandle
while (<$fh>) { } Read file line by line
print $fh "text"; Write to filehandle
die "Error: $!" unless $fh; Die with error message ($! = system error)
-e $file File exists test
-r -w -x Readable, writable, executable tests
-d $path Directory test

Subroutines

sub name { } Define subroutine
name(); Call subroutine
@_ Array of arguments
my ($a, $b) = @_; Unpack arguments
return $val; Return value
shift; Get first argument (shifts @_)

Modules & CPAN

use Module; Import module at compile time
require Module; Load module at runtime
cpan Module::Name Install CPAN module
cpanm Module::Name Install with cpanminus (faster)
use LWP::Simple; Web client module
use DBI; Database interface
use JSON; JSON encoding/decoding
use Data::Dumper; Debug data structures

Useful Functions

chomp $str; Remove trailing newline
length $str String length
uc $str / lc $str Uppercase / lowercase
substr $str, 0, 5 Substring (offset, length)
index $str, "sub" Find substring position
rand 100 Random float 0-100
int rand 100 Random integer 0-99
time Unix timestamp
sleep 5; Sleep 5 seconds

Command-Line One-Liners

perl -pe 's/old/new/g' file Search and replace in file
perl -ne 'print if /pattern/' file Grep for pattern
perl -i -pe 's/old/new/g' file In-place edit (modifies file)
perl -MData::Dumper -e 'print Dumper \%ENV' Dump environment variables
Pro Tips:
  • Always use strict and warnings: Catch errors early and enforce good practices
  • Regex is Perl's superpower: Unmatched text processing capabilities
  • CPAN has everything: 180,000+ modules for any task imaginable
  • One-liners for quick tasks: -p for line-by-line processing, -e for inline code
  • $_ is your friend: Default variable used by many functions
  • chomp for input: Always chomp when reading user input to remove newlines
  • File tests (-e, -r, -d): Check file properties before opening
  • Data::Dumper for debugging: Visualize complex data structures
← Back to Data Science & ML | Browse all categories | View all cheat sheets