in reply to Anonymous Thingies
my @array1 = (1, 2, 3, 4); my @array2 = (5, 6, 7, 8); my @master_array = ( \@array1, \@array2 );
Great, now you have a 2d array, and you can dereference it like this:
print $master_array[0][2], "\n"; # prints '3'
But what a pain, having to keep track of all those @array1, @array2, etc. And even more of a pain it is if somehow you modify an element in @array1, and forget that it is going to propigate through to the same element within @master_array.
So there's an easier way.....
my @master_array = ( [1, 2, 3, 4], [5, 6, 7, 8] );
Now you have the same contents in @master_array: a two dimensional array. But you also have completely bypassed all the trouble of creating temporary sub-arrays. In this example, @master_array contains two anonymous arrays of four elements each.
You can take it a step further. Perhaps you have a function that takes an array ref as parameter. Maybe you don't need that array to ever have a real name, just a reference to it. So that's when you would use an anonymous array as the top level of the structure.
As for scoping, as long as someone knows about the anonymous array, it remains in existance. By "knows about", I mean, as long as something refers to it, and that something is still in scope, the anonymous array will remain alive and there. Perl uses a "reference count" method of garbage collection. Each time something points to a piece of information, that piece of information (the scalar, or whatever) has one added to its reference count. As the things that point to it fall from scope or get pointed elsewhere, the reference count drops. It's not until nothing is pointing to (or referencing) it that it gets 'reaped'.
The same principles apply to other anonymous thingies such as hashes and functions too. Imagine how useful it is to be able to utilize complex data structures by virtue of anonymous thingies.
References don't care whether the thing they point to has a name in the symbol table or not. As long as the thingy has a positive reference count, it will remain in existance.
I strongly recommend looking at the following resources that are available online or at your local Perl installation:
At some point through that reading assignment a lightbulb will come on and you'll say, "Oh, that makes sense."
To directly respond to your questions.....
* Why would you want such a thing?
* What's the scope on an anonymous thingie?
* Will they ever die/get lost/get clobbered?
Dave
|
|---|