Perl Cheatsheet
Scripting Patterns
Use this Perl reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Main Function Pattern
use v5.36; sub main (@args) { # parse, validate, work, print return 0; } exit main(@ARGV);
Validation
die "usage: $0 <file>\n" unless @ARGV == 1; my $path = shift @ARGV; open my $fh, '<', $path or die "$path: $!";
Option Parsing with Getopt::Long
use Getopt::Long qw(GetOptions); my $verbose = 0; my $output = "out.txt"; GetOptions( "verbose|v" => \$verbose, "output|o=s" => \$output, ) or die "bad options\n";
Line Filter One-Liners
perl -ne 'print if /ERROR/' app.log perl -pe 's/foo/bar/g' file.txt perl -lane 'print $F[0]' data.txt
One-Liner Flags
| Flag | Meaning |
|---|---|
-e | code follows on command line |
-E | like -e plus modern features such as say |
-n | loop over input, do not auto-print |
-p | loop over input and auto-print $_ |
-a | autosplit into @F |
-l | handle line endings with print/chomp style behavior |
-i | edit files in place, optionally with backup suffix |
Error Handling
open my $fh, '<', $path or die "$path: $!"; warn "skipping bad row $.\n"; my $data = eval { decode_json($raw) }; # trap a die from library code if ($@) { warn "bad JSON, skipping: $@"; }
die with a trailing newline suppresses the "at FILE line N" suffix. See the Control Flow and Subs page for try/catch (stable since Perl 5.40) and Try::Tiny.
Practical Text Pipeline
while (my $line = <STDIN>) { chomp $line; next if $line =~ /^\s*$/; $line =~ s/^\s+|\s+$//g; my @fields = split /\s*,\s*/, $line; print join("\t", @fields), "\n"; }