O'Reilly logo

Learning Perl, Fourth Edition by brian d foy, Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required