Reputation: 4417
Here is my Perl code:
use strict;
use warnings;
my @words = ("alpha", "bravo", "charlie");
(my $word = $_) foreach @words;
print $word;
I would expect this code to do one of two things:
$word
after the loop is complete.my $word
is a lexical variable whose scope is the foreach
loop; it does not exist at the final line.Instead, it seems the value of $word
is undef
, and Perl raises a warning and prints the empty string.
Why?
Upvotes: 1
Views: 137
Reputation: 50677
From perldoc perlsyn
NOTE: The behaviour of a my, state, or our modified with a statement modifier conditional or loop construct (for example, my $x if ... ) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.
Upvotes: 6