Working with arrays and hashes

push, sort, map and grep, slices, exists, // for defaults, and counting with a hash.

Runs in Zerethon IDE · Perl 5.40 Official Perl documentation ↗
main.pl
use v5.40;

my @scores = (70, 95, 82);
push @scores, 60;
my @sorted = sort { $a <=> $b } @scores;
say "@sorted | $scores[0] $scores[-1] ", scalar @scores;
say join(",", @sorted[1, 2]);

my %ages = (ada => 36, alan => 41);
$ages{grace} = 85;
say $ages{linus} // "unknown", " ", exists $ages{alan} ? "yes" : "no";
for my $name (sort keys %ages) {
    say "$name $ages{$name}";
}

my @squares = map { $_ * $_ } grep { $_ % 2 == 0 } 0 .. 4;
say "@squares";

my %count;
$count{$_}++ for qw(a b a c a);
say join ", ", map { "$_=$count{$_}" } sort keys %count;

Output

60 70 82 95 | 70 60 4
70,82
unknown yes
ada 36
alan 41
grace 85
0 4 16
a=3, b=1, c=1
  • An array inside double quotes is joined with spaces: "@sorted".
  • map transforms each element and grep keeps the elements whose block is true; inside both, the element is $_.
  • Hash order is random. Use sort keys %hash when the order matters.
  • $value // "default" gives the default when the value is undef.
  • qw(a b c) is a list of words without quotes and commas.