Another Example: Alphabetical Lists of Names

For another example, let's put together hashes and split into a simple example that reads a list of names, puts those names into a hash keyed by last name, and then prints out the list in alphabetical order, last name first. Here's an example of what it looks like:

Enter a name (first and last): Umberto Eco
Enter a name (first and last): Isaac Asimov
Enter a name (first and last): Fyodor Dostoyevski
Enter a name (first and last): Albert Camus
Enter a name (first and last): Bram Stoker
Enter a name (first and last): George Orwell
Enter a name (first and last):
Asimov, Isaac
Camus, Albert
Dostoyevski, Fyodor
Eco, Umberto
Orwell, George
Stoker, Bram

Listing 5.2 shows our short little script to read and adjust the data.

Listing 5.2. The names.pl Script
1:  #!/usr/local/bin/perl -w
2:
3:  $in = '';      # temporary input
4:  %names = ();   # hash of names
5:  $fn = '';      # temp firstname
6:  $ln = '';      # temp lastname
7:
8:  while () {
9:      print 'Enter a name (first and last): ';
10:     chomp($in = <STDIN>);
11:     if ($in eq '') { last; }
12:
13:     ($fn, $ln) = split(' ', $in);
14:     $names{$ln}  = $fn;
15: }
16:
17: foreach $lastname (sort keys %names) {
18:     print "$lastname, $names{$lastname} 
";
19: }

This script has three basic sections: initialize the variables, read in the data, and print it back out again. I'll skip the initialization part because that should be obvious by now.

Lines 8 through 15 read the data in a way that should look familiar from the statistics script, using a while loop, an if to test for an empty entry, and <STDIN> in a scalar context. Unlike stats, where we put the elements into an array, line 13 uses split to separate the name input into two temporary scalar variables, $fn and $ln. Then in line 14, we add that first and last name pair to the $names hash, with the last name as the key.

With the hash all set up with the data, we can go ahead and print it. Again, you've seen this syntax before, most recently in the histogram example previously in this lesson. Here, we're sorting the keys in alphabetical order, so we can use the simpler form of sort here. And, finally, the print statement in line 18 uses the $lastname variable (which contains the current key) and the hash lookup for that key to print out the first and last names.

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

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