Hashes (Associative Arrays)

This section deals with a special kind of array in Perl called a hash. Hashes, sometime called associative arrays, contain paired data. Each pair in the hash contains a key that acts as an index to a value that is associated with it. Hashes represent a simple yet powerful idea whose use makes programs more efficient and maintainable.

Hash Functionality

In this section we explore the functionality built into Perl for manipulating hashes. We start with an example hash that maps rock groups to their lead singers. See the folder Groups.


% type groups.pl
#
#   groups.pl
#
%groups = (  U2 => Bono,
             Stones => "Mick Jagger",
             Aerosmith => "Steve Tyler",
             Heartbreakers => "Tom Petty",
             Journey => "Steve Perry",
             Queen => "Freddie Mercury",
          );
while(1)
{
     print "Enter a Rock Super Group ('quit' to quit) ";
     chomp($group = <STDIN>);
     last if ($group =~ /^quit/i);
     print "Lead singer for $group is $groups{$group}
";
}
% perl groups.pl
Enter a Rock Super Group ('quit' to quit ) U2
Lead singer for U2 is Bono
Enter a Rock Super Group ('quit' to quit ) Queen
Lead singer for Queen is Freddie Mercury
Enter a Rock Super Group ('quit' to quit ) Beatles
Lead singer for Beatles is
Enter a Rock Super Group ('quit' to quit ) quit
%

The big advantage of a hash is that the programmer does not have to perform a lookup. The expression $groups{$group} uses the variable $group as the index to the value associated with it. If you happen to evaluate this expression for a pair that is not present, then the output is simply empty. You can see that occurring above when the user asks for the Beatles. Note also that the {}'s are used to index a hash, whereas the []'s are used to index an array. This is because in Perl the same program could have an array and a hash with the same name.

Incidentally, the %groups hash could also have been formed using the array initialization syntax. In this case, for each pair of elements within parentheses, the first item is the key and the second item is the value.

%groups=(  U2, Bono, Stones, "Mick Jagger", Aerosmith,
           "Steve Tyler", Heartbreakers, "Tom Petty",
           Journey, "Steve Perry", Queen,"Freddie Mercury"
           );

It is also possible to take an existing array and assign it to a hash, as shown below. When you do this, be sure that the pairs are arranged correctly.

@groups= (U2, Bono, Stones, "Mick Jagger", Aerosmith,
          "Steve Tyler", Heartbreakers, "Tom Petty",
          Journey, "Steve Perry", Queen,
          "Freddie Mercury"
          );
%groups = @groups;

EXISTS

Before you actually form an expression such as $groups{$groups}, you are advised to check whether that entry exists. You can use the function exists for this purpose. Rather than indiscriminately printing the value of $groups{$group}, you should first determine if there is an entry for this key. Thus, the code above should have been written as

if ( exists ($groups{$group}) )
{
    print "Lead singer for $group is $groups{$group}
";
}
else
{
    print "No information on $group
";
}

ADDING AND DELETING VALUES

Although most problems involving hashes call for the direct lookup of an entry in the hash table, problems involving hashes are dynamic. This means that when the program is executing, there are often requests for adding and deleting entries. To delete an entry, simply code as follows, using the delete function.

if ( exists( $group{$group} ) )
{
   delete $groups{$group}
}

Adding an element is as simple as the following.

$groups{Eagles} = "Don Henley";
$groups{Wings} = "Paul McCartney";

KEYS AND VALUES

There are many occasions when you must know the entire set of keys. You can use the keys function for this. The code below can be used to retrieve the keys.

foreach $key (keys(%groups))
{
    print ++$i, "	", $key, "
";
}

1   Heartbreakers
2   Journey
3   Aerosmith
4   Stones
5   Queen
6   U2

You may have noticed that the keys are displayed in no special order. If you want to impose an order on them, you can sort the keys first.

foreach $key (sort (keys(%groups)))
{
    print ++$i, "	", $key, "
";
}

1   Aerosmith
2   Heartbreakers
3   Journey
4   Queen
5   Stones
6   U2

You can also retrieve all the values whenever you wish by using the values function.

foreach $value (values(%groups))
{
    print ++$i, "	", $value, "
";
}

1   Tom Petty
2   Steve Perry
3   Steve Tyler
4   Mick Jagger
5   Freddie Mercury
6   Bono

EACH

Another function that may prove useful for manipulating hashes is the each function. This function delivers each pair in some unspecified order until there are no more pairs. The following idiom can be used to iterate over all the pairs.

while(($key, $value) = each(%groups))
{
    print "$key -> $value
";
}

Heartbreakers -> Tom Petty
Journey -> Steve Perry
Aerosmith -> Steve Tyler
Stones -> Mick Jagger
Queen -> Freddie Mercury
U2 -> Bono

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.103.8