Pass the Envelope
Let us say we are given a text file containing Academy Award (Oscar) winners by year and category, formatted as follows:
1995:Actor:Nicholas Cage 1995:Picture:Braveheart 1995:Supporting Actor:Kevin Spacey 1994:Actor:Tom Hanks 1994:Picture:Forrest Gump 1928:Picture:WINGS
We would like to provide the following services:[16]
Given a year and category, print the corresponding entry.
Given a year, print all entries for that year.
Given a category, print the year and title of all entries for that category.
Print all entries sorted by category or by year.
Data Representation
Since we would like to retrieve entries by category or by year, we use a double indexing scheme, as shown in Figure 2.2.
Figure 2-2. Data structure to represent Oscar winners
Each entry includes a category, a year, and the name of the
corresponding winner. We choose to keep this information in an
anonymous array (an anonymous hash would do just as well). The two
indices %year_index
and
%category_index
map the year and category to
anonymous arrays containing references to the entries. Here is one
way to build this structure:
open (F, "oscar.txt") || die "Could not open database: $!"; %category_index = (); %year_index = (); while ($line = <F>) { chomp $line; ($year, $category, $name) = split (/:/, $line); create_entry($year, $category, $name) if $name; } sub create_entry { # create_entry (year, category, name) ...
Get Advanced Perl Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.