qntm
qntm

Reputation: 4417

Why doesn't this lexical variable retain its value after the loop?

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:

  1. Print the string "charlie", which is the final value of $word after the loop is complete.
  2. Complain of a compilation error, since 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

Answers (1)

mpapec
mpapec

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

Related Questions