Promotion of undef variable to ARRAY ref in foreach

Viewed 51
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?

1 Answers

Autovivification makes

@$x

equivalent to

@{ $x //= [] }

in lvalue context.

Use

if ($x) {
   for (@$x) {
      ...
   }
}
Related