Not multidimentional arrays - but lists of lists. Much more flexible. Perl!
Archive - Originally posted on "The Horse's Mouth" - 2011-08-26 19:28:37 - Graham EllisIn Perl, you don't have multidimensional structures as such - you have list and hashes ... and you can have lists of hashes, hashes of lists and hashed of hases too. Which give you almost all of the benefits of multi dimensional structures, but with few of the limitations. And they can be set up in short pieces of code too.
while (<s;>) {
my @hit = split;
push @accesses,\@hit;
}
Each line from a data file named on the command line is read into $_. (<> defaults to reading from a file named on the command line, and in a while statement it's saved into $_ unless the code specifies somewhere else).
The line is split into a list of fields, the separator between the fields being white spaces. (split uses white space and $_ as its defaults).
Onto a list called @accesses, we add a reference to (i.e. the address of the list @hit). The very first time through the loop, the list is created and it's automatically extended each time.
On reaching the } at the end of the loop, the name @hit is released as this was a "my" variable scoped to the block. However, since the actual data is now referenced within the @accesses list, the memory that it has used will be retained ... resulting in a new location for a new @hit next time around the loop!
So - having set up that data, how do we access it?
print ${$accesses[100]}[9],"\n";
That's "Look at contents of the 100th element of the @accesses list and within the list that's pointed to there look at the contents of the 9th element" [but counted in each case from 0 not 1, so really the 10th element of the 101st row].
We could make that a bit easier:
print $accesses[100]->[9],"\n";
The -> operator has replaced ${---} - it's just a syntactic change, but never the less it helps with followability, and indeed I can also write:
print $accesses[100][9],"\n";
According to the rules of the language, I shouldn't be able to do this ... except that wehn Perl sees two subscripts butted up against each other without any opertor in between them, it assumes the author wanted -> ... which usually he did!