Hashes
A hash, sigil %, stores unordered key-value pairs. Individual values are read and written with $hash{key} — note the sigil switches to $ again, since a single value is a scalar. keys returns a list of all the keys, and values returns a list of all the values, in the same (unspecified, but internally consistent) order. sort keys %hash is the idiomatic way to get a predictable, alphabetical iteration order.
use strict;
use warnings;
my %ages = (Alice => 30, Bob => 25, Carol => 35);
for my $name (sort keys %ages) {
print "$name is $ages{$name}\n";
}
print "Values: ", join(", ", sort { $a <=> $b } values %ages), "\n";
Alice is 30 Bob is 25 Carol is 35 Values: 25, 30, 35
=> is just a more readable alias for the comma inside a list literal — Alice => 30 means exactly the same thing as "Alice", 30. exists checks whether a key is present without the side effect of autovivifying it (creating it with an undef value just by looking it up), and delete removes a key-value pair entirely.
use strict;
use warnings;
my %ages = (Alice => 30, Bob => 25);
print "Has Alice? ", (exists $ages{Alice} ? "yes" : "no"), "\n";
print "Has Dave? ", (exists $ages{Dave} ? "yes" : "no"), "\n";
delete $ages{Alice};
print "Has Alice after delete? ", (exists $ages{Alice} ? "yes" : "no"), "\n";
Has Alice? yes Has Dave? no Has Alice after delete? no
Next: context — the single most distinctive idea in Perl, and the thing this course has been quietly foreshadowing since the introduction.
Practice exercise
Create my %capitals = (France => "Paris", Japan => "Tokyo"), then print the capital of Japan.