http://www.perlmonks.org?node_id=1090329

mfort has asked for the wisdom of the Perl Monks concerning the following question:

Script:
#!/usr/bin/perl print "test=$test\n"; print "this won't be printed\n" if (scalar @{$test}[0]); print "test=$test\n";
Output:
test= test=ARRAY(0x7fcc8c004ee8)
In a larger script, $test will either be undef or will be a reference to an array of data, where the first element is an array reference. I would have expected 'scalar' to examine only, not create an anonymous array. So what is the logic employed by perl?

Replies are listed 'Best First'.
Re: Why will referencing an undefined value as array reference create a real array
by jeffa (Bishop) on Jun 18, 2014 at 18:54 UTC

    That's a feature called auto-vivification. Consider the following alternative:

    print "this won't be printed\n" if (scalar @{$test} and scalar @{$test +}[0]);

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      Thanks for pointing me to the Auto Vivification. I swear I learn something new every day with perl and I've been using it for decades now.
Re: Why will referencing an undefined value as array reference create a real array
by Anonymous Monk on Jun 18, 2014 at 18:57 UTC
Re: Why will referencing an undefined value as array reference create a real array
by LanX (Saint) on Jun 19, 2014 at 02:55 UTC
    > ... or will be a reference to an array of data, where the first element is an array reference.

    Why don't you just use ref for your check?

    Cheers Rolf

    (addicted to the Perl Programming Language)

Re: Why will referencing an undefined value as array reference create a real array
by ikegami (Patriarch) on Jul 29, 2014 at 14:43 UTC
Re: Why will referencing an undefined value as array reference create a real array
by sundialsvc4 (Abbot) on Jun 19, 2014 at 13:44 UTC

    That was a conscious design-decision by the language designers ... and a very good one, indeed.   When you refer to an as-yet undefined variable in a particular context, it will automagically become a reference to an empty instance of whatever is appropriate to that context ... “auto-vivification,” as previously stated.   An incredibly useful feature of the language for pragmatic script-writing.