Learn/Perl/7. Arrays and hashes
Lesson 7 of 8
Sign in

Perl, lesson 7

Arrays and hashes

Scalars hold one value. For many values Perl has two more variable types, each with its own sigil: arrays (@) for ordered lists and hashes (%) for key/value lookups.

Arrays

Notice the sigil changes to $ when you get one item: $scores[0] is a single scalar out of the array @scores. The sigil tells you what you get back, not what you're looking in.

An array used where Perl expects a single value (like in scalar(@scores), or my $n = @scores) gives its length. $#scores is the index of the last item.

Growing and shrinking

2 exercises to try what you just read.

Exercise 1

Score stats

Press Ctrl Enter or Check to test your code.

Exercise 2

Shopping list

Press Ctrl Enter or Check to test your code.

Looping, joining, sorting

sort returns a sorted copy. By default it sorts as strings, which puts 100 before 9. For numbers, give it a comparison block using the special variables $a and $b and the "spaceship" operator <=>:

For strings, the comparison operator is cmp. Because $a and $b are special to sort, don't use them as your own variable names.

Inside double quotes, an array interpolates with spaces between the items: "@scores" gives 70 85 92.

Hashes

A hash maps keys (strings) to values:

As with arrays, a single value uses the $ sigil, and the key goes in curly braces. Looking up a missing key gives undef.

Counting with a hash is one of Perl's favourite tricks. Adding to an undef value treats it as 0, so there is no need to check first:

Looping over a hash

keys %hash gives the keys in no particular order. Sort them when the order matters:

Further reading

  • perlintro: Arrays and hashes
  • perldata: List value constructors
  • perlfunc: sort
  • perlfunc: keys

Read one line of whole-number game scores separated by spaces (at least one score). Print:

Sample input:

Sample output:

Several people added items to a shared shopping list, so the same item can appear more than once. The first line is the number of entries. Each entry line has an item name and a quantity separated by a space. Add up the quantity for each item and print one line per item, <item>: <total>, in alphabetical order.

Sample input:

Sample output:

my @scores = (70, 85, 92);
print "$scores[0]\n";          # 70   (indexes start at 0)
print scalar(@scores), "\n";   # 3    (number of items)
print "$scores[-1]\n";         # 92   (negative indexes count from the end)
push @scores, 60;          # add to the end
my $last = pop @scores;    # remove from the end
unshift @scores, 50;       # add to the front
my $first = shift @scores; # remove from the front
for my $score (@scores) {
    print "$score\n";
}

print join(", ", @scores), "\n";   # 70, 85, 92
my @nums = sort { $a <=> $b } (12, 4, 100, 9);   # 4 9 12 100
my @desc = sort { $b <=> $a } @nums;             # 100 12 9 4
my @words = sort @names;                         # alphabetical
my %stock = (apple => 5, pear => 2);
print "$stock{apple}\n";      # 5
$stock{kiwi} = 7;             # add or change a key
delete $stock{pear};          # remove a key
print "yes\n" if exists $stock{apple};
my %count;
$count{$_}++ for qw(red blue red);   # red => 2, blue => 1
for my $item (sort keys %stock) {
    print "$item: $stock{$item}\n";
}
Count: <how many>
Highest: <max>
Lowest: <min>
Sorted: <scores from low to high, separated by spaces>
70 92 85 64
Count: 4
Highest: 92
Lowest: 64
Sorted: 64 70 85 92
4
milk 2
eggs 12
milk 1
bread 1
bread: 1
eggs: 12
milk: 3