Perl: More on Lists and Hashes (
Page 1 of 4 )
Welcome to the first part of what should be the final two articles in our series on working with hashes and lists in Perl. This makes our eleventh article in the series and in it, we will wrap up the intermediate ways of working with hashes and lists. We'll learn to add rows and columns to a two-dimensional list, replace them, create multi-dimensional lists, and write hashes and files to lists, then open and read from those same files over the next two articles.Just as a refresher, in our previous article we went into detail about just what exactly a two-dimensional list was, how to print a single record from them and how to print an entire row. We also explained how to create variables, lists, and hashes using a two-dimensional array.
Setting Up the “Database”
I like to throw around that word two-dimensional. You'll find it runs rampant throughout this article (and the last one). It's a big word that soothes my little mind. So try not to get too annoyed as you see it thrown carelessly about.
For starters, let's create a two-dimensional list for a book collection. Much to the chagrin of my girlfriend I have about nine billion books and nowhere to put them. So with this article I will try to appease her by adding some to a database. Here are the fields of data that will appear in our “database”:
-
Book Number
-
Author
-
Title
-
Genre
-
Number of Stars (how good the book was in a ranking of 1-5, with five being the best)
-
Which shelf on the bookshelf it is located
Here is the code to create the list and print it out to make sure everything is correct:
#!/usr/bin/perl
@Bookshelf = (
[" # ", " Author ", " Title ", " Genre "," Rating "," Location " ],
[' 1 ', ' Stephen King ', ' It ', ' Horror ', ' 5 ', ' Top '],
[' 2 ', ' Clive Barker ', ' Imajica ', ' Horror ', ' 5 ', ' Top '],
[' 3 ', ' Neil Gaiman ', ' American Gods ', ' Dark Fantasy ',' 5 ',
' Top '],
[' 4 ', ' Dean Koontz ', ' Tick-Tock ', ' Horror ', ' 1 ', '
GarbageCan '],
[' 5 ', ' Charles Bukowski ', ' Letters from a Dirty Old Man ', '
Literature ', ' 5 ', ' Top '],
[' 6 ', ' Chuck Pahluniak ', ' Fight Club ', ' Dark Fantasy ', ' 5 ', ' Middle ']
);
print "\n\n";
print @{@Bookshelf[0]};
print "\n";
print @{@Bookshelf[1]};
print "\n";
print @{@Bookshelf[2]};
print "\n";
print @{@Bookshelf[3]};
print "\n";
print @{@Bookshelf[4]};
print "\n";
print @{@Bookshelf[5]};
print "\n";
print @{@Bookshelf[6]};
print "\n";
print @{@Bookshelf[7]};
Here, in the above code, we created a fake set of headers to print out, which occupy row 0. When we print this code we get the following result:
# Author Title Genre Rating Location
1 Stephen King It Horror 5 Top
2 Clive Barker Imajica Horror 5 Top
3 Neil Gaiman American Gods Dark Fantasy 5 Top
4 Dean Koontz Tick-Tock Horror 1 GarbageCan
5 Charles Bukowski Letters from a Dirty Old Man Literature 5 Top
6 Chuck Pahluniak Fight Club Dark Fantasy 5 Middle