[Melbourne-pm] Perl switch statements

Jacinta Richardson jarich at perltraining.com.au
Mon Oct 22 22:10:07 PDT 2012

On 23/10/12 11:04, Mathew Robertson wrote:
> To clarify, I would have expected $x to not be lexical... I am 
> deliberately reusing $x in the child scope assignment, without 
> localising $x (via 'my' or 'local'):
> my $x = 'foo';
> foreach $x (1..2) {
>   foreach $x ('a'..'c') {
>     print $x." ";
>   }
>   print $x." ";
> }
> print $x.$/;
> gives: a b c 1 a b c 2 foo
> when I told the code to generate: a b c c a b c c c

$x is lexical. That's what declaring it with a my does... except...
you'll find that the following two loops are effectively identical.

foreach $x ( 1..10) {

     say $x;




     local $x = 1;

     while( $x < 10 ) {

         say $x;



Notice that extra set of parentheses and the local?

As per <perldoc perlsyn> this is intentional:

       The "foreach" loop iterates over a normal list value and sets the
        variable VAR to be each element of the list in turn.  If the 
        is preceded with the keyword "my", then it is lexically scoped, 
and is
        therefore visible only within the loop. _/*Otherwise, the 
variable is*/__/*
*/__/*       implicitly local to the loop and regains its former value 
upon exiting*/__/*
*/__/*       the loop.*/_  If the variable was previously declared with 
"my", it uses
        that variable instead of the global one, but it's still localized to
        the loop.  This implicit localization occurs only in a "foreach" 

No point arguing, it's existed this way for a long, long time.  ;)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/melbourne-pm/attachments/20121023/ddf8ec5a/attachment.html>

More information about the Melbourne-pm mailing list