in reply to Erroneous defined detection of array elements

exists is a better test for hash and array elements, and will not auto-vivify them.
perl -le ' $a[10] = 1; if (exists $a[2]) { print "how did that get there?\n"; } else { print "a[2] does not exist\n"; } ' a[2] does not exist

Replies are listed 'Best First'.
Re^2: Erroneous defined detection of array elements
by ikegami (Patriarch) on Nov 23, 2009 at 20:38 UTC

    That's bad advice. You should never have to use exists on an array element. It returns useless information and doesn't solve the problem you claims it solves (as explained by almut).

    See modules autovivification and warnings::autoviv. (Well, the latter doesn't exist yet. Working on it.)

Re^2: Erroneous defined detection of array elements
by almut (Canon) on Nov 23, 2009 at 20:24 UTC
    and will not auto-vivify them

    defined will not autovivify either:

    my @array; if (defined $array[20]) { } # no autovivific +ation, thus if (defined $array[20]) { warn "[20] does exist!" } # no warning

    Typically, it's a dereferencing operation that unexpededly autovivifies.  exists shares the same problem:

    my @array; if (exists $array[20]->[42]) { } if (exists $array[20]) { warn "[20] does exist!" } __END__ [20] does exist! at ./808911.pl line 5.
      I should have been more clear - defined does not distinguish between "never existed" and "is undef" for hash and array elements. I therefore consider exists a better test for unexpected auto-vivification.

        defined does not distinguish between "never existed" and "is undef" for hash and array elements.

        Neither does exist. It checks if the element currently exists, not if the element has ever existed.

        Either way, so what?

        I therefore consider exists a better test for unexpected auto-vivification.

        That makes no sense. It doesn't prevent autovivification. It doesn't tell you whether something was autovivified or not. It doesn't help at all.

        $ perl -le'{ my @a; $a[15][0]; print "After autovivification: ", exists($a[14]) || 0, exists($a[15]) || 0, defined($a[14]) || 0, defined($a[15]) || 0; }{ my @a; $a[15] = []; print "After explicit vivification: ", exists($a[14]) || 0, exists($a[15]) || 0, defined($a[14]) || 0, defined($a[15]) || 0; }' After autovivification: 0101 After explicit vivification: 0101