Perl Cheatsheet

Arrays and Hashes

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

Arrays

my @items = ("a", "b", "c");
my @nums = 1..5;                       # 1,2,3,4,5
my @words = qw(red blue green);        # quoted words

$items[0]                              # first element
$items[-1]                             # last element
scalar @items                          # length
$#items                                # last index

Array Operations

push @items, "d";                      # add end
my $last = pop @items;                 # remove end
unshift @items, "z";                   # add front
my $first = shift @items;              # remove front
my @part = splice @items, 1, 2;        # remove 2 from index 1
@items = reverse @items;               # reverse returns a new list
my @sorted = sort @items;              # string sort, original unchanged
my @asc = sort { $a <=> $b } @nums;    # numeric sort

reverse and sort never modify their arguments. In void context (sort @items;) they do nothing, and use warnings reports "Useless use of sort in void context". Always assign the result.

Slices

my @some = @items[1..3];               # array slice (note the @ sigil)
my @vals = @score{qw(Ada Grace)};      # hash slice of values
my %pair = %score{qw(Ada Grace)};      # key-value hash slice (5.20+)
@score{qw(Linus Ken)} = (88, 90);      # assign several keys at once

List Tools

my @squares = map { $_ * $_ } @nums;
my @even = grep { $_ % 2 == 0 } @nums;
my $csv = join ",", @items;
my @fields = split /,/, $csv;

Sorting Recipes

my @by_num = sort { $a <=> $b } @nums;             # ascending numeric
my @desc   = sort { $b <=> $a } @nums;             # descending numeric
my @by_len = sort { length($a) <=> length($b) } @words;

# multi-key: score descending, then name ascending
my @ranked = sort {
    $b->{score} <=> $a->{score}
        or
    $a->{name} cmp $b->{name}
} @rows;

Hashes

my %score = (
  Ada => 95,
  Grace => 99,
);

$score{Ada}                             # value for key Ada
$score{Linus} = 88;                     # assign new key
exists $score{Ada};                     # key exists
defined $score{Ada};                    # value is not undef
delete $score{Linus};

Hash Iteration

for my $key (sort keys %score) {
    print "$key $score{$key}\n";
}

while (my ($key, $value) = each %score) {
    print "$key=$value\n";
}

Counting Pattern

my %count;
for my $word (@words) {
    $count{$word}++;
}