Perl Hashes
A hash stores key/value pairs: look up a value by its key, as in a dictionary or phone book. Hash variables start with %. Keys are strings; values are any scalars.
use strict;
use warnings;
my %capital = (
France => "Paris",
Japan => "Tokyo",
Kenya => "Nairobi",
);
print "Capital of Japan: $capital{Japan}\n";
$capital{Peru} = "Lima"; # add a pair
$capital{France} = "Paris"; # overwrite (same value here)
print "Countries: ", scalar(keys %capital), "\n";Capital of Japan: Tokyo
Countries: 4
The fat comma => works like a comma but quotes the word on its left, so you can write France => "Paris" instead of "France", "Paris". A single value is a scalar, so you access it with $ and curly braces: $capital{Japan}.
Hash order is random
A hash has no order. Perl even randomises the order on purpose for security, so it can change from one run to the next. When you need a stable order, sort the keys:
use strict;
use warnings;
my %price = (tea => 3.5, coffee => 4, juice => 5.25, water => 1);
foreach my $item (sort keys %price) {
printf "%-7s %5.2f\n", $item, $price{$item};
}
print "Cheapest first: ";
print join(", ", sort { $price{$a} <=> $price{$b} } keys %price), "\n";coffee 4.00
juice 5.25
tea 3.50
water 1.00
Cheapest first: water, tea, coffee, juice
Tip: Never rely on the order of
keys,valuesoreach. Alwayssortwhen the output order matters.
exists, delete and defined
use strict;
use warnings;
my %login = (alice => "2024-05-01", bob => undef);
for my $user (qw(alice bob carol)) {
my $state = !exists $login{$user} ? "unknown user"
: !defined $login{$user} ? "never logged in"
: "last login $login{$user}";
print "$user: $state\n";
}
delete $login{bob};
print "After delete: ", join(", ", sort keys %login), "\n";alice: last login 2024-05-01
bob: never logged in
carol: unknown user
After delete: alice
exists asks "is this key present?", while defined asks "is the value not undef?". delete removes the pair entirely.
Iterating
keys returns all keys, values all values, and each returns one key/value pair at a time:
use strict;
use warnings;
my %inventory = (bolts => 120, nuts => 75, screws => 300);
my $total = 0;
$total += $_ for values %inventory;
print "Total parts: $total\n";
for my $part (sort keys %inventory) {
print "$part => $inventory{$part}\n";
}Total parts: 495
bolts => 120
nuts => 75
screws => 300
Counting with a hash
The single most common hash idiom is counting how often something occurs. A missing key reads as undef, and ++ on undef gives 1, so no setup is needed:
use strict;
use warnings;
my @votes = qw(red blue red green blue red);
my %count;
$count{$_}++ for @votes;
for my $color (sort { $count{$b} <=> $count{$a} || $a cmp $b } keys %count) {
print "$color: $count{$color}\n";
}
my %seen;
my @unique = grep { !$seen{$_}++ } @votes;
print "Unique in order: @unique\n";red: 3
blue: 2
green: 1
Unique in order: red blue green
The grep { !$seen{$_}++ } line is a famous idiom: the first time a value is seen, $seen{$_} is 0 (false), so ! makes it true and the value is kept; afterwards it is positive and the value is dropped.
Hash slices and conversion
use strict;
use warnings;
my %user = (name => "Kim", age => 34, city => "Seoul", role => "dev");
my @info = @user{qw(name city)}; # hash slice: list of values
print "Info: @info\n";
my %subset = %user{qw(name role)}; # key/value slice
print join(", ", map { "$_=$subset{$_}" } sort keys %subset), "\n";
my %by_value = reverse %user; # swap keys and values
print "Who is 34? $by_value{34}\n";Info: Kim Seoul
name=Kim, role=dev
Who is 34? age
reverse on a hash turns values into keys; it only works well when the values are unique.
Test yourself
How do you read the value for key apple from %stock?
%stock{apple}$stock[apple]$stock{apple}@stock{apple}
What is the difference between exists $h{k} and defined $h{k}?
- None
existschecks the key is present;definedchecks the value is not undefdefineddeletes the keyexistsonly works on arrays
Why do examples use sort keys %h when printing?
keysonly works with sort- Hash order is unpredictable, so sorting gives a stable order
- It is faster
- It removes duplicate keys