[Date Prev][Date Next][Thread Prev][Thread Next]
[Search]
[Date Index]
[Thread Index]
Re: [MacPerl-AnyPerl] perl whine
On Thu, 8 Jun 2000 11:51:16 -0400, Eric Rainey wrote:
>and I say print ${$$ref[2]}[0];
>
>Then it prints nothing, but suddenly $ref is now
>
> $ref-> [
> anon1->[0,1,2],
> anon2->[0,1,2],
> anon3->[]
> ]
>
>and if you have a conditional which checks for the existence $ref[2]
>being not true to stop a loop, suddenly you're toast.
>
>Is this behavior helpful sometimes?
Sure it is. It's a feature called "autovivication".
Suppose @$ref only had elements 0 and 1. And then you do:
push @{$ref->[2]}, 'boo!';
In this case, it will do the right thing (IMO), and create a new empty
anonymous array, at $ref->[2], and add 'boo!' in it, as the first
element.
It's even more useful with hashes. Look at this example:
#!perl -w
$\ = "\n";
use Data::Dumper;
while(<DATA>) {
chomp;
my($key, $value) = split /\s+/, $_, 2 or next;
push @{$related{$key}}, $value;
}
print Dumper(\%related);
__DATA__
Fred Wilma
Barney Betty
Barney Bam Bam
Fred Dino
Fred Pebbles
Imagine how complicated the script would have to be without
autovivication!
I can understand the gripe about this autovivication when only trying to
*read* a value. You could call it a bug.
In you particular case, you may get around it by doing
print ref($ref[2]) && ${$$ref[2]}[0];
which also has the advantage of eliminating a possible "use of
uninitialized value" warning.
p.s. I prefer the syntax $ref->[2][0] over what you've used.
print ref($ref->[2]) && $ref->[2][0];
--
Bart.
==== Want to unsubscribe from this list?
==== Send mail with body "unsubscribe" to macperl-anyperl-request@macperl.org