Hashes
A hash stores pairs of keys and values so you can look things up by name.
In this page:
Hashes
Hash names start with % and you fetch a value with $hash{key}. Keys are strings and the order of keys is not defined, so sort keys when you need predictable output. Use exists to test for a key, delete to remove one, and keys, values and each to walk through the contents.
Note:
The fat comma => quotes the word on its left, so you can write name => "Ada" without quotes around name.
Example: Hashes
use strict;
use warnings;
my %ages = (
Alice => 30,
Bob => 25,
);
$ages{Carol} = 41;
print "Bob is $ages{Bob}\n";
print "Has Dave? ", (exists $ages{Dave} ? "yes" : "no"), "\n";
delete $ages{Bob};
for my $name (sort keys %ages) {
print "$name => $ages{$name}\n";
}
print "count: ", scalar(keys %ages), "\n";
my %inverse = reverse %ages;
print "who is 30? $inverse{30}\n";
# Output:
# Bob is 25
# Has Dave? no
# Alice => 30
# Carol => 41
# count: 2
# who is 30? Alice
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Relying on a particular key order
- Using exists on the value instead of the key
- Writing $hash{key} when the hash is called %hash but using @ or % on the element
Chapter Summary
- Hashes start with %
- Values use $hash{key}
- Key order is not guaranteed so sort keys
- exists and delete work on keys
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: