in reply to Why nothing from 'strict' or 'warnings' with deref'd undef value?

( Please use <c> instead of <pre>. Less work for you, more features for us. )

Append the following, and you'll see why it's not an error:

print "$array_ref->[0]\n";

You asked for a hash reference, so Perl obliged rather that giving an error. It's a very convenient (although sometimes problematic) feature called "autovivification". Solution:

use strict; use warnings; my $array_ref = [undef]; if ( $array_ref->[0] # <--- && $array_ref->[0]->{whatever} ) { print "true\n"; } else { print "false\n"; }

Note that the arrow is optional between indexes, so
$array_ref->[0]->{whatever}
can be written as
$array_ref->[0]{whatever}

Replies are listed 'Best First'.
Re^2: Why nothing from 'strict' or 'warnings' with deref'd undef value?
by jeremym (Initiate) on Apr 02, 2009 at 23:45 UTC
    Thanks for the <c> tip! I'll be sure to do that from now on.

    This all makes sense and my exact example is even right there in the PerlDoc! Time to read up again or get better at Googling...

    What is a valid use for autovivification outside of an assignment operation? I can certainly see the value of
    $ref->[0]{field} = "value";
    but I don't see how my first example can be very useful without an assignment.

      That very question just came up on p5p, the Perl developers' mailing list. It turns out that some rvalue operations autovivify and some don't. Spoke Nicolas Clark, the pumpking:

      So why are indexing and defined special?
      Are they the only exceptions to the exception?

      No answer was obtained.

      Source: Perl RT 63810

        Perfect - exactly what I was looking for. Additional examples are even more interesting.

        Thank you for everything.