← Back to Perl Course | Chapter 2: Variables | Lesson 5 of 7

Hashes

A hash stores pairs of keys and values so you can look things up by name.

In this page:

  1. Hashes

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

perl
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
Common Mistakes
  1. Relying on a particular key order
  2. Using exists on the value instead of the key
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.