Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl vivification question while dereferencing undefined array reference

I'm having tough time in understanding why the following works:

my $array_reference;
foreach $element (@{$array_reference}) {
# some code
}

while the following does not work

my $array_reference;
if (scalar (@{$array_reference}) {
    # some code here
}

I understand that perl brings to life (auto-vivifies) undefined reference. But I am still confused as in why the latter code segment throws FATAL.

like image 941
kuriouscoder Avatar asked Jun 21 '11 02:06

kuriouscoder


2 Answers

Dereferences autovivify in lvalue context (meaning when a modifiable value is expected), and foreach create an lvalue context.

>perl -E"$$x = 1;  say $x;"
SCALAR(0x74b024)

>perl -E"++$$x;  say $x;"
SCALAR(0x2eb024)

>perl -E"\$$x;  say $x;"
SCALAR(0x30b024)

>perl -E"sub {}->($$x);  say $x;"
SCALAR(0x27b03c)

>perl -E"for ($$x) {}  say $x;"
SCALAR(0x25b03c)

The last two create an lvalue context because they need a value to which to alias $_[0] and $_ (respectively).

like image 200
ikegami Avatar answered Oct 05 '22 08:10

ikegami


Perl has inconsistencies in this area, but in general, code that may modify a structure autovivifies, while code that won't doesn't. And if it doesn't autovivify, it is trying to dereference an undefined value, which triggers a warning, or, under use strict "refs", an exception.

like image 23
ysth Avatar answered Oct 05 '22 07:10

ysth