Typical Use of a Hash

At this point, a concrete example might help.

The Bedrock library uses a Perl program in which a hash tracks how many books each person has checked out:

    $books{"fred"} = 3;
    $books{"wilma"} = 1;

It’s easy to see if an element of the hash is true or false; do this:

    if ($books{$someone}) {
      print "$someone has at least one book checked out.\n";
    }

But there are some elements of the hash that are false:

    $books{"barney"} = 0;       # no books currently checked out
    $books{"pebbles"} = undef;  # no books EVER checked out - a new library card

Since Pebbles has never checked out any books, her entry has the value of undef, rather than 0.

There’s a key in the hash for everyone who has a library card. For each key (or library patron), the value is the number of books checked out or undef if that person’s library card has never been used.

The exists Function

To see if a key exists in the hash, (whether someone has a library card), use the exists function, which returns a true value if the given key exists in the hash, whether the corresponding value is true or false:

    if (exists $books{"dino"}) {
      print "Hey, there's a library card for dino!\n";
    }

That is to say, exists $books{"dino"} will return a true value if (and only if) dino is found in the list of keys from keys %books.

The delete Function

The delete function removes the given key (and its corresponding value) from the hash. (If there’s no such key, its work is done; there’s no warning or error in that case.)

 my $person = "betty"; ...

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.