appleii has asked for the wisdom of the Perl Monks concerning the following question:

Hi, monks. I wrote the below code to test. Why the variable $n was undef? I wonder what's the difference between a foreach construct and an if construct in this case. Thanks for any help.
#!/bin/env perl use strict; use warnings; my $n = $_ foreach (1 .. 2); warn "\$n = $n"; my $m = 1 if (1); warn "\$m = $m";

Replies are listed 'Best First'.
Re: Why the variable $n was undef?
by ikegami (Patriarch) on Aug 16, 2010 at 13:31 UTC
    my ... for ...; and my ... if ...; are not valid constructs. The results are undefined. The first doesn't even make any sense.
Re: Why the variable $n was undef?
by Corion (Patriarch) on Aug 16, 2010 at 12:58 UTC

    See perlsyn on Foreach-Loops. The looop variable gets localized, that is, at loop end its value gets restored to what it was before the loop started.

      That may be true, but it's complete irrelevant. $n isn't the loop variable, $_ is.

      IMO, this is a bug. Either there's an assumed block around the statement, or there isn't. If there is, the use of $n afterwards should be a compile time error; if it isn't, $n should be 2 afterwards. (As if the my wasn't in the same line).

      and this?
      our $n = $_ foreach (1 .. 2); warn "\$n = $n";

        See my and our to find the difference.

        Just a something something...