Perl · Course navigation

Perl Hashes

Map keys to values and print them in a stable order.

On this page
Before you start

Perl arrays.

  • Map keys to values and print them in a stable order.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

A hash variable starts with %. It stores key-value pairs, and a single value is read with $scores{Ada}, with a $ and curly braces. Adding a key is just assigning to it.

Perl does not promise any order for hash keys, and the order can change between runs. keys %scores returns the keys, and sort puts them in a predictable alphabetical order before the loop.

Code example

Perl
use strict;
use warnings;

my %scores = (Ada => 91, Grace => 88);
$scores{Linus} = 79;
for my $name (sort keys %scores) {
    print "$name: $scores{$name}\n";
}
Output
Ada: 91
Grace: 88
Linus: 79

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1use strict;
2use warnings;
3
4my %scores = (Ada => 91, Grace => 88);
5$scores{Linus} = 79;
6for my $name (sort keys %scores) {
7 print "$name: $scores{$name}\n";
8}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
A hash with two pairs; => quotes the bare words.%scores has 2 pairs
—
Add a third key.%scores has 3 pairs
—
Visit the keys alphabetically: Ada, Grace, Linus.%scores has 3 pairs
—
Print each pair.%scores has 3 pairs
Ada: 91
Grace: 88
Linus: 79

Behind the scenes

How Perl processes this code

Perl compiles the script internally before executing it. strict and warnings help identify mistakes.

Cost and common mistakes

Lookup is O(1) on average; the sorted loop is O(k log k) for k keys.

  • Without sort, the key order is unspecified.
  • Reading a missing key returns undef, which warns when printed under use warnings.

Try it yourself

Remove Grace before the loop.

Reveal answer and reasoning

Use delete $scores{Grace}; only Ada and Linus are printed.

Further reading