View Single Post
  #8   (View Single Post)  
Old 6th February 2014
ocicat ocicat is offline
Administrator
 
Join Date: Apr 2008
Posts: 3,318
Default

Quote:
Originally Posted by thirdm View Post
... then I would be wondering why you hadn't simply written

print "'$k'\t'$h{$k}'\n" if $h{$k}
Modify the posted code to the following:
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/]); 

print '=' x 4, $/;
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 $h{$k};
}
print '=' x 4, $/;
for my $k (keys %h) {
    print "'$k'\t'$h{$k}'\n" if defined $h{$k};
}
$ 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 13.
'undef_element' ''
'zero_string'   '0'
'empty_string'  ''
====
====
'zero_value'    '0'
'zero_string'   '0'
'empty_string'  ''
$
Testing against the element's value all evaluates to false in these cases.

Last edited by ocicat; 6th February 2014 at 08:32 PM.
Reply With Quote