Hash Element Access

To access an element of a hash, use syntax that looks like this:

    $hash{$some_key}

This is similar to what we used for array access, but here we use curly braces instead of square brackets around the subscript (key).[161] That key expression is now a string, rather than a number:

    $family_name{"fred"} = "flintstone";
    $family_name{"barney"} = "rubble";

Figure 6-3 shows how the resulting hash keys are assigned.

Assigned hash keys

Figure 6-3. Assigned hash keys

This lets us use code like this:

    foreach $person (qw< barney fred >) {
      print "I've heard of $person $family_name{$person}.\n";
    }

The name of the hash is like any other Perl identifier (letters, digits, and underscores, but it can’t start with a digit). And it’s from a separate namespace; that is, there’s no connection between the hash element $family_name{"fred"} and a subroutine &family_name, for example. Of course, there’s no reason to confuse everyone by giving everything the same name. But Perl won’t mind if you have a scalar called $family_name and array elements like $family_name[5]. We humans will have to do as Perl does; we’ll have to look to see what punctuation appears before and after the identifier to see what it means. When there is a dollar sign in front of the name and curly braces afterward, it’s a hash element that’s being accessed.

When choosing the name of a hash, it’s often nice to think of the word “for” between ...

Get Learning Perl, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.