Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promotion of undef variable to ARRAY ref in foreach

Tags:

perl

use strict;                  
use warnings FATAL => 'all'; 

my $x = undef;               
if (@$x) { print "ok\n" }    
else { print "no\n" } 

Predictably yields "Can't use an undefined value as an ARRAY reference" for if (@$x). But inserting a foreach (@$x):

use strict;                  
use warnings FATAL => 'all'; 

my $x = undef;               
foreach (@$x) { print $_ }  # <------- 
if (@$x) { print "ok\n" }    
else { print "no\n" }        

print ref($x)."\n"; 

Outputs:

no
ARRAY

The foreach line seems to have made an assignment to $x. What's up with this?

like image 544
CodeClown42 Avatar asked Oct 18 '25 06:10

CodeClown42


1 Answers

Autovivification makes

@$x

equivalent to

@{ $x //= [] }

in lvalue context.

Use

if ($x) {
   for (@$x) {
      ...
   }
}
like image 53
ikegami Avatar answered Oct 22 '25 05:10

ikegami