Typical Use of a Hash
At this point, you may find it helpful to see a more concrete example.
The Bedrock library uses a Perl program in which a hash keeps track of how many books each person has checked out, among other information:
$books{"fred"} = 3;
$books{"wilma"} = 1;It’s easy to see whether 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 aren’t true:
$books{"barney"} = 0; # no books currently checked out
$books{"pebbles"} = undef; # no books EVER checked out - a new library cardSince 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 (that is, for each library patron), there’s a value that is
either a number of books checked out, or undef if that person’s library card has never
been used.
The exists Function
To see whether a key exists in the hash, (that is, whether
someone has a library card or not), use the exists function, which returns a true value
if the given key exists in the hash, whether the corresponding value
is true or not:
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. ...