Home arrow Perl Programming arrow Page 3 - Hash Functions

Hash Functions - Perl

In this second part of a two-part series on hashes in Perl, you'll learn about hash functions and hashes in different contexts. This article is excerpted from chapter five of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).

TABLE OF CONTENTS:
  1. Hash Functions
  2. Hash in Scalar Context
  3. Hash Functions
  4. Hash Examples
  5. Counting Things
By: Apress Publishing
Rating: starstarstarstarstar / 1
May 06, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Since hashes in list context are apparently random collections of key/value pairs, we canít really use foreach loops on them directly. If we did, we would get both keys and values with no indication as to which was which. To help us, Perl provides three functions for iterating over hashes:keys(),values(), and
each().

Also, Perl provides functions to remove elements (delete(), already seen previously), and to check to see if a key exists in the hash (exists()).

The keys() Function

First, there is keys(%hash). This gives us a list of the keys (all of the scalars on the left-hand side). This is usually what we want when we wish to visit each hash entry in turn as shown in this example:

#!/usr/bin/perl -w
# keys.pl

use strict;

my %where = (
        Gary     => "Dallas",
        Lucy     => "Exeter",
        Ian      => "Reading",
        Samantha => "Oregon"
);

foreach (keys %where) {
    print "$_ lives in $where{$_}\n";
}

Currently, this tells us

$ perl keys.pl
Lucy lives in Exeter
Samantha lives in Oregon
Gary lives in Dallas
Ian lives in Reading
$

You may find that the output appears in a different order on your machine.1 Donít worry. As mentioned before, hashes are unordered, and thereís no guarantee that the keys will come out in the same order each time. It really depends on the particular version of Perl that you are using.

Letís look at the part of the program that does all the work:

foreach (keys %where) {
    print "$_ lives in $where{$_}\n";
}

keys()is a function which, likesort()andreverse(), returns a list. The list in this case is
qw(Lucy Samantha Gary Ian), and theforeachloop visited each of those values in turn. As$_was set to each one, we could print the name and look up that entry in the hash.

The values() Function

The counterpart to keys() isvalues(), which returns a list of all of the values in the hash. This is somewhat less useful, since you can always find the value if you have the key, but you cannot easily find the key if you have the value. Itís almost always advantageous to usekeys()instead.

Here is an example using thevalues()function:

#!/usr/bin/perl -w
# values.pl

use strict;

my %where = (
        Gary     => "Dallas",
        Lucy     => "Exeter",
       
Ian      => "Reading",
        Samantha => "Oregon"
);

foreach (values %where) {
    print "someone lives in $_\n";
}

1. Or even different every time that you run it! Some 5.8.x Perl installations have hash order randomization turned on by default.

Executing this program produces the following:

$ perl values.pl
someone lives in Exeter
someone lives in Oregon
someone lives in Dallas
someone lives in Reading
$

The each() Function

The next hash function is each(). It returns each hash entry as a key/value pair. Normally, the values returned are copied into an assignable list like this:

each() . It returns hash entry as a key/value pair. Normally, the values returned are copied into an assignable list like this:The next hash function is each(). It returns hash entry as a key/value pair. Normally, the values returned are copied into an assignable list like this:

($k, $v) = each %where;

This is illustrated ineach.pl:

#!/usr/bin/perl -w
# each.pl

use strict;

my %where = (
        Gary     => "Dallas",
        Lucy     => "Exeter",
        Ian      => "Reading",
        Samantha => "Oregon"
);

my($k, $v);
while (($k, $v) = each %where) {
    print "$k lives in $v\n";
}

Here is an example of this program executing:

$ perl each.pl
Lucy lives in Exeter
Samantha lives in Oregon
Gary lives in Dallas
Ian lives in Reading
$

The delete() Function

We have already seen the delete() function. It removes a key/value pair from a hash. This statement frombadhash.plremoves the pair Lucy/Exeter from
%where:

delete $where{Lucy};

Since we are on the subject, we should mention that thedelete()function also deletes array elements. The following code would remove element 3 from the array@array. Note that the element returns to an uninitialized state:

delete $array[3];

The exists() Function

The last function we will look at is the exists() function. It returns true if the key exists in the hash, false if not. Here is an example:

exists() function. It returns true if the key exists in the hash, false if not. Here is an example:The last function we will look at is the exists() function. It returns true if the key exists in the hash, false if not. Here is an example:

#!/usr/bin/perl -w
# exists.pl


use strict;

my %where = (
        Gary     => "Dallas",
        Lucy     => "Exeter",
        Ian      => "Reading",
       
Samantha => "Oregon"
);

print "Gary exists in the hash!\n" if exists $where{Gary};
print "Larry exists in the hash!\n" if exists $where{Larry};

Running this program results in the following:

$ perl exists.pl
Gary exists in the hash!
$


Note  exists()returns 1 when true, an empty string when false.


Theexists()function also works for array elements. This code checks to see if element 3 exists in@array:

if (exists $array[3]) {
   
print "element 3 exists!\n";
}



 
 
>>> More Perl Programming Articles          >>> More By Apress Publishing
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: