The difference between named and anonymous data lies in the way how they are stored and addressed:
Named Anonymous
@array []
%hash {}
If you say somewhere in your code
@array;
the named array @array is created, and it's there, you can use it later to stuff things in. Whereas if you say
[];
you create an anonymous array, and on the next line it's gone. Why? The creation of an anonymous array returns a pointer to where that array is allocated. If you don't store that pointer somewhere, it's gone, and the anonymous array too. If you create a named array, the array is "contained in the name", for anonymous arrays you have to store its location somewhere:
$arrayref = [];
Now you have the reference to that anonymous array in you scalar variable $arrayref, and you can pass this pointer around, or fill the anonymous array pointed at by dereferencing it:
$ary = $arrayref;
push @$ary,"foo";
print $arrayref->[0]; # prints "foo" \
print @$arrayref[0]; # prints "foo" - same pointer value in $ary and
+$arrayref
print $ary->[0]; # prints "foo" /
So a named array has a name, which is the word after the sigil '@', while an anonymous array only has a location somewhere in perl's memory.
we all knew that the implicit variable here is $_ that is being printed out.
This "implicit variable" has nothing to do with an array, but with the for iterator. You can use that with literals too:
for("foo") {
print; # prints foo
undef $_; # dies with "Modification of a read-only value attempte
+d"
# - literals cannot be modified
}
The variable $_ is not attached to an array, it just happens to be the global default variable a.k.a The Thing (which in a for loop is aliased, so for works with its own version and doesn't stomp on other operator's idea of what $_ is).
so in connection with creating anonymous data structures below:
my $ref = ["my","list"];
what would be that implicit name (variable) that was created? and how can i access it?
There is no implicit name - all there is is a pointer. If you force that pointer to be a string (e.g. by saying print $ref), perl translates the pointer into something readable (e.g. ARRAY(0x8166c28)).
All you have is a scalar variable $ref, to which you assigned the pointer to an anonymous array. You have to dereference that address pointer if you want to loop over the anonymous array - the loop body is exactly the same:
for (@$ref) {
print;
$_ = undef;
}
# the [] array pointed to with the content of $ref is now [undef,undef
+]
See perlref for further information.
--shmem
_($_=" "x(1<<5)."?\n".q·/)Oo. G°\ /
/\_¯/(q /
---------------------------- \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
|