View Single Post
  #5   (View Single Post)  
Old 6th February 2014
ocicat ocicat is offline
Join Date: Apr 2008
Posts: 3,297

Originally Posted by thirdm View Post
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:
$ cat ./                                                                                         
#!/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 ./
$ ./                                                                                           
$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 ./ 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.

Last edited by ocicat; 6th February 2014 at 07:40 PM. Reason: remove dangling articles... :)
Reply With Quote