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

FlagMeaning
-ecode follows on command line
-Elike -e plus modern features such as say
-nloop over input, do not auto-print
-ploop over input and auto-print $_
-aautosplit into @F
-lhandle line endings with print/chomp style behavior
-iedit 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";
}