Perl Cheatsheet

Algorithm Practice

Use this Perl reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Fast Problem Skeleton

Perl is usually chosen for scripting and text processing, but the same arrays, hashes, loops, and sorting tools are useful for small algorithm practice tasks and coding interview problems.

#!/usr/bin/env perl
use v5.36;

my @lines = <STDIN>;
chomp @lines;

# parse input, solve, print one answer per line
say solve(@lines);

Parse Space-Separated Numbers

my $n = <STDIN>;
chomp $n;
my @nums = split ' ', <STDIN>;

split ' ' (a literal single space) is special-cased: it splits on any whitespace run and discards a leading empty field. split /\s+/ keeps an empty first field when the line starts with whitespace, so prefer split ' ' for tokenizing input.

Frequency Map

Hashes are the default Perl data structure for counts, membership checks, and many data structures and algorithms exercises.

my %count;
for my $x (@nums) {
    $count{$x}++;
}

for my $key (sort { $a <=> $b } keys %count) {
    say "$key $count{$key}";
}

Two-Pointer Pattern

my @a = sort { $a <=> $b } @nums;
my ($left, $right) = (0, $#a);

while ($left < $right) {
    my $sum = $a[$left] + $a[$right];
    if ($sum == $target) { say "found"; last; }
    elsif ($sum < $target) { $left++; }
    else { $right--; }
}

Memoized Recursion

my %memo;
sub fib ($n) {
    return $n if $n < 2;
    return $memo{$n} //= fib($n - 1) + fib($n - 2);
}

List::Util Shortcuts

use List::Util qw(sum0 min max first uniq reduce);

my $total = sum0 @nums;              # 0 for an empty list
my ($lo, $hi) = (min(@nums), max(@nums));
my $hit = first { $_ > 10 } @nums;
my @distinct = uniq @nums;
my $product = reduce { $a * $b } 1, @nums;