home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book HomeLearning Perl, 3rd EditionSearch this book

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

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.