Perl Programming Page 3 - Perl: Bon Voyage Lists and Hashes |
Again, push() works in the same manner as it did with normal lists; that is, it adds a record to the rightmost position (or end) of a two-dimensional list: #!/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 '] ); push(@Bookshelf, [' 1 ', ' T.H. White ', ' The Once and Future King ','Fantasy ', ' 5 ', ' Middle ']); print @{@Bookshelf[7]}; This code places the “Once and Future King” book at the end of the list, which we then print out in the final line of code, resulting in:
You can also do the same thing using a variable to insert the data, like so: #!/usr/bin/perl @NewBook = (' 1 ', ' T.H. White ', ' The Once and Future King ','Fantasy ', ' 5 ', ' Middle '); @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 '] ); push(@Bookshelf, [@NewBook]); print @{@Bookshelf[7]}; Here, we create a variable called @NewBook and store some info about T.H. White's book inside of it. Next we created @Bookshelf and stored even more information into it. Finally, we used push() to append the data in @NewBook to the end of @Bookshelf. When we print out the last element, this is what we get:
That's right...the same as before. Pop and Shift As you will recall from previous articles, Pop() removes items from the right side of a list and shift removes items from the left side of a list. Since I have already covered these two in the past, and since I have shown how to use Unshift and Push on two dimensional lists above, I won't cover them again here, in an effort to save space and not be too repetitive. If you would like to read more about them, then simply follow this link: http://www.devshed.com/c/a/Perl/Perl-Lists-More-on-Manipulation/
blog comments powered by Disqus |
|
|
|
|
|
|
|