Perl Arrays

   



Perl Hashes

Hashes in Perl are similar to hashes in Java or 'associative arrays' in awk (named after Aho, Weinberger, and Kernighan). One of the key strengths of hashes in Perl is the ease with which you can create multi-dimensional hashes and then sort and traverse the stored values. Listing C.5 demonstrates how to create a two-dimensional Perl hash that associates a integer-valued scalar with a set of people who are identified by their first name and last name.

Listing C.5 simpleHash1.pl

start example
my($lastName)     = ""; my($employeeId)   = ""; my(%Employees);     $Employees{"Jones"} = 2000; $Employees{"Smith"} = 2000; $Employees{"Smith"} = 3000; foreach $lastName (keys %Employees) {    $employeeId = $Employees{$lastName};    {       print "$lastName has Id = $employeeId\n";    } }
end example

Remarks

You can launch the Perl script simpleHash1.pl in Listing C.5 from the command line as follows,

perl -w simpleHash1.pl

and the output is as follows

Jones has Id = 2000 Smith has Id = 3000

If you want to sort the elements of a hash, you can use something like the following,

foreach $lastName (sort (keys %Employees))

and if you want to list the elements of a hash in reverse sorted order, you can do so as follows:

foreach $lastName (reverse (sort (keys %Employees)))

As you've probably noticed, one drawback to one-dimensional hashes is obvious: you cannot distinguish between two people with the same last name. The next example shows how to create a two-dimensional hash to handle this situation.



   



Fundamentals of SVG Programming. Concepts to Source Code
Fundamentals of SVG Programming: Concepts to Source Code (Graphics Series)
ISBN: 1584502983
EAN: 2147483647
Year: 2003
Pages: 362

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net