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?
Autovivification makes
@$x
equivalent to
@{ $x //= [] }
in lvalue context.
Use
if ($x) {
for (@$x) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With