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

The code below gives error Global symbol "$x" requires explicit package name.

use strict; use warnings; sub f { $_[0]==15 } if((my $x=15) && f($x)) { print "OK\n" }'
Now I admit that this is a somewhat unconventional construct, but taking the perl docs at face value, I thought this should work. For instance, my says
A "my" declares the listed variables to be local (lexically) to the enclosing block, file, or "eval".
which means that $x should be interpreted as lexical, not global, in the call of f. Further, && guarantees left-to-right evaluation, so $x should be defined when f is called, so I had expected the output of the program being OK. Of course I can easily rewrite it by declaring $x one line earlier, but I wonder why it does not work the way I tried it.

-- 
Ronald Fischer <ynnor@mm.st>

Replies are listed 'Best First'.
Re: Declaring a lexical within a 'if' condition
by kennethk (Abbot) on Mar 03, 2010 at 16:04 UTC
    You've created an unnecessarily complex example to replicate your observation - you get the same error with:

    use strict; (my $x = 15) && $x;

    and obviously the following does not throw the error:

    use strict; (my $x = 15);$x;

    Unfortunately I don't have a good why scoping behaves the way it does in these examples - I would naively expect the my statement to execute before the second term in the conditional was evaluated. I found the documentation you want to read. From Private Variables via my() in perlsub:

    The declared variable is not introduced (is not visible) until after the current statement.

    So there you go. I assume the design logic is so the following works-as-hoped:

    my $x = 1; for (1 .. 5) { my $x = $x; $x += $_; print $x; } print $x;
      > The declared variable is not introduced (is not visible) until after the current statement.

      exactly, it's meant to allow constructs like my $x=f($x) where the new lexical can be initialized with help from the old scope!

      Cheers Rolf