in reply to Re: Hashing it out: defined? exists?
in thread Hashing it out: defined? exists?

Which of these approachs autovivifies a hash entry? I know from the exists docs that the exists test won't autovivify. I'm pretty sure the last test will autovivify. I'm not sure about defined, though.

Replies are listed 'Best First'.
Re^3: Hashing it out: defined? exists?
by ikegami (Patriarch) on Sep 02, 2005 at 19:59 UTC

    None of them will.

    { my %h; 1 if exists $h{key}; print("exists: ", (%h ? "auto-vivi" : "empty"), "\n"); } { my %h; 1 if defined $h{key}; print("defined: ", (%h ? "auto-vivi" : "empty"), "\n"); } { my %h; 1 if $h{key}; print("true: ", (%h ? "auto-vivi" : "empty"), "\n"); } __END__ exists: empty defined: empty true: empty

    The following are the only forms of auto-vivification that come to mind:

    # If $h{$i} and $a[$i] are not defined, $h{$i}{$j} # Creates a hash and stores a ref to it in $h{$i}. $h{$i}[$j] # Creates an array and stores a ref to it in $h{$i}. $a[$i]{$j} # Creates a hash and stores a ref to it in $a[$i]. $a[$i][$j] # Creates an array and stores a ref to it in $a[$i].
      Thanks for the info. The exists documentation does warn that your first example of autovivification ($h{$i}{$j}) will autovivify even if you're checking with exists. That is,
      { my %h; 1 if exists $h{foo}{bar}; print("exists 2: ", (%h ? "auto-vivi" : "empty"), "\n"); }
      prints "auto-vivi".

      But for some reason I thought it was easier to autovivify keys.

        Keys are never auto-vivified. They are always created through assignment (incl the implicit assignment of an autovivified hash or array as shown in an earlier post).
        $h{$k} = $v; @h{$k} = ($v); %h = ($k, $v); # Also removes everything else.
        .