On Sun, Jun 6, 2010 at 10:49, Philip Potter <[email protected]> wrote:
> On 6 June 2010 14:37, Shawn H Corey <[email protected]> wrote:
>> On 10-06-06 09:06 AM, Chas. Owens wrote:
>>>
>>> But that is not the problem; autovivification will create the references:
>>>
>>> perl -MData::Dumper -le '$c->[0]{a}; print Dumper $c'
>>>
>>
>> But that is the problem. Autovivification should not happen for r-values,
>> only l-values.
>
> I take it you mean it should only happen when you write to a location
> ($c->[3] = 'foo') not when you read from a location (print $c->[3]) ?
> I would think that $c->[0]{a} is an lvalue by most definitions - it's
> a value which can be written to. It's an lvalue even when on the right
> side of an assignment.
snip
Don't get caught up in the definition of lvalue. The point he is making is that
my %foo;
if ($foo{bar}{baz}) {
print $foo->{bar}{baz}
}
should not autovivify and that
my $foo;
if ($foo->{bar}{baz}) {
print $foo->{bar}{baz}
}
should die with a message about $foo not being a hashref, but that
my %foo;
$foo{bar}{baz} = 1;
should autovivify. To safely write the first case in Perl 5, you must write
if (exists $foo{bar} and $foo{bar}{baz}) {
}
Otherwise the key "bar" will be added to %foo with the value of an
empty anonymous hashref. For more complex data structures it gets
even worse:
if (exists $h{a} and exists $h{a}{b} and exists $h{a}{b}{c} and
$h{a}{b}{c}{d}) {
}
--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/