Perl Hashes
Map keys to values and print them in a stable order.
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
Explanation
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.
Explore the dry run
Guided walkthroughReady
1
use strict;2
use warnings;3
4
my %scores = (Ada => 91, Grace => 88);5
$scores{Linus} = 79;6
for 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
| Step / line | What happens | State after step | Output 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 |
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.