Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

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.

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page