Perl Programming Page 3 - Perl: More on Lists and Hashes |
Just as you can add a row to the end of a list, you can also add a column, though in truth it is a little more complex. In the sample below we are going to add a column to the end of each row. It will hold a value of “READ”, meaning of course that we have read the book. You may recall from an earlier article how to use the for loop. If not, don't worry too much about it. Shortly we will be going more in-depth on loops (in another article or two in fact). Here is the awe-inspiring code: #!/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 '] ); $NumRows = @Bookshelf; for($i = 0; $i < $NumRows; $i +=1) { $Bookshelf[$i][7] = "READ"} print @{@Bookshelf[5]}; After creating our two-dimensional list and assigning values to it, we then create a variable called $NumRows and assign it the value of @Bookshelf. However, since a variable cannot contain a 2-D list, the number of rows is instead store in the variable. Which is exactly what we intended. Next we create a for loop that appends a new column with the value of “READ” to the end of each row. Finally, we print out the fifth row, just to ensure that it worked, giving us the result: 5 Charles Bukowski Letters from a Dirty Old Man Literature 5 Top READ Of course we may not wish to automatically assign the same exact value to the end of each row, but the code for that is a little beyond the scope of this article. If you are curious as to how the for loop works, here is a break down: the $i=0 part is the counter variable. $i < $NumRows is the criteria. Basically this says do this loop while $i is less than $NumRows. Finally, we have the incrementer, $i +=1. This adds one to the counter variable each time through the loop. The statement: { $Bookshelf[$i][7] = "READ"} adds a column to a different row each time through the loop (with the value “READ”). The loop breaks when the value in $i is greater than the value in $NumRows.
blog comments powered by Disqus |
|
|
|
|
|
|
|