Quote:
Originally Posted by thirdm
As far as I can tell, in boolean context a hash entry that doesn't exist will yield false, as will an entry that's there but undef, as will one that's there but one of the other false values (0, "", "0"). Neither does it seem like referring to a non-existent element will either cause a warning or autovivify anything.
|
Unfortunately, I don't have as complete an answer as I would like, but I have probably coded similar ambiguities myself, & the following code demonstrates a common issue:
Code:
$ cat ./test.pl
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my %h = ( zero_value => 0, zero_string => '0', empty_string => '', undef_element => undef );
print Data::Dumper->Dump([\%h], [qw/h/]);
for my $k (keys %h) {
print "'$k'\t'$h{$k}'\n";
}
print '=' x 4, $/;
for my $k (keys %h) {
print "'$k'\t'$h{$k}'\n" if defined $h{$k};
}
$ chmod +x ./test.pl
$ ./test.pl
$h = {
'zero_value' => 0,
'undef_element' => undef,
'zero_string' => '0',
'empty_string' => ''
};
'zero_value' '0'
Use of uninitialized value $h{"undef_element"} in concatenation (.) or string at ./autovivify.pl line 12.
'undef_element' ''
'zero_string' '0'
'empty_string' ''
====
'zero_value' '0'
'zero_string' '0'
'empty_string' ''
$
I agree that autovivification
shouldn't be the issue
(& those interested should review the documentation for defined()...), but I have been burnt by undefined hash elements before
(as demonstrated by the example above...) which was alleviated by brute force use of
defined().
So to further this hand-waving explanation, I would say that the practice is simply stylistic. Plus, I haven't taken the time to fully grok the CVS history.