In Perl keys get defined if they are accessed as hash, without checking for their existence

In the following code snippet, 'c' is not as key in 'foo' but is set to {} when the last check for foo->c->0 is called.

/tmp()$ cat foo.pl
use strict;
use warnings;
use Data::Dumper;

sub abcde {
   my $foo = {'a' => 1, 'b' =>2};
   print Dumper($foo);

   if (exists $foo->{c} && defined $foo->{c}->{0}) {
      print "C is defined";
   }
   print Dumper($foo);

   if (defined $foo->{c} and defined $foo->{c}->{0}) {
      print "C is defined";
   }
   print Dumper($foo);

   if (defined $foo->{c}->{0}) {
      print "C is defined";
   }
   print Dumper($foo);

}

abcde();
/tmp()$ perl foo.pl 
$VAR1 = {
          'a' => 1,
          'b' => 2
        };
$VAR1 = {
          'a' => 1,
          'b' => 2
        };
$VAR1 = {
          'a' => 1,
          'b' => 2
        };
$VAR1 = {
          'c' => {},
          'a' => 1,
          'b' => 2
        };

Comments

Popular posts from this blog

Multiple repeat error when the regex has multiple wildcards in python re module

Weakref proxy is for instance only ...

To speed up accessing files on nfs shares on a ubuntu machine ...