in reply to Re: Scoping of my with foreach loop
in thread Scoping of my with foreach loop
Not quite.
do_something_with( $item );
will always be the same as
do_something_with( undef );
in your code. foreach restores the initial value when the loops exits (in effect), as seen in the following snippet:
use strict; my @values = (1, 2, 3, 'a', 4); my $item = 'z'; foreach $item (@values) { last if $item =~ /[^\d]/; } print($item); # Prints 'z', not 'a'.
I thought it might be using a localized global when my is omitted, but it's clearly not the case:
use strict; sub test { our $item; print("[$item]"); } { my @values = (1, 2, 3, 'a', 4); my $item = 'z'; foreach $item (@values) { test(); last if $item =~ /[^\d]/; } print($item); } # Outputs "[][][][]z" # Changing "my $item" to "our $item" # changes the output to "[1][2][3][a]z"
This is perl, v5.6.1 built for MSWin32-x86-multi-thread
|
|---|