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