Perl Programming Page 4 - Perl: A Continuing Look at Hashes and Multidimensional Lists |
Two-dimensional lists are lists that have other lists as their items. Go ahead. Grab that mop and clean up the mess I just made by making your head explode. In the next few examples, we are going to pretend that we have a database of lame superheroes that just never made it. Each record will consist of the following:
Let's go ahead and create our first two-dimensional array: #!/usr/bin/perl @StuporHeroes = ( [' Mount Tittikanaka ', ' Man-Girl ', ' Is a good listener ', ' Has Man-Boobs '], ['Trailer Park', 'Deaf Leapard', 'Has a super sonic guitar', 'Is deaf and has one arm making him unable to play his guitar'] ); In the above example, we created a two-dimensional list named @StuporHeroes. You will note that even though our list has an added dimension, we still use the @ symbol before the name, just as with our normal lists. We then encase the values in our two-dimensional list with square brackets, instead of parentheses as per normal lists. Each piece of data or “cell” is separated by a comma. Each row of data is placed between a set of parentheses, ending in a semi-colon, as shown above. If this seems a little confusing at the moment, that is all right. When I explain them in the next section everything will become crystal clear. Better Understanding the Two-Dimensional List The best way to think of a two-dimensional list is to imagine an Excel sheet. I used that same analogy with hashes, but really it applies more to this storage device. For instance, in a spreadsheet you enter data into a grid, like the one shown below:
@StuporHeroes = ( [' Mount Tittikanaka ', ' Man-Girl ', ' Is a good listener ', ' Has Man-Boobs '], ['Trailer Park', 'Deaf Leapard', 'Has a super sonic guitar', 'Is deaf and has one arm making him unable to play his guitar'] ); Our first row contains all of the following data: “Mount Tittikanaka”, “Man-Girl”, “Is a good listener” and “Has man boobs”. Note that with lists, element numbers start at 0. All of these elements have a row number of zero. However there column number differs. If I wanted to call on “Mount Tittikanaka” for instance, I would search for the value in row 0, column 0. If I wanted “Man-Girl”, I would search in row 0, column 1, and so forth. The second row contains the values: “Trailer Park”, “Deaf Leapard”, “Has a super sonic guitar”, and “Is deaf and has one arm making him unable to play his guitar”. If I wanted to refer to “Trailer Park” I would point to row 1, column 0. “Deaf Leopard” is located at row 1 and column 1. Always keep in mind that elements start at 0 (as do our rows and columns). Well that's it for this article. In our next episode we will learn to print from our extra-dimensional lists, and figure out other ways to manipulate the data contained within them. So be sure to stop back often! Till then...
blog comments powered by Disqus |
|
|
|
|
|
|
|