This is a real issue that bites people from time to time, and it seems to me that it could be fixed with a minor extension of syntax to specify that a foreach loop should not do aliasing. Of course, it can also be addressed by a little code (and awareness):
my $n; # Going to set this
for my $a (1..100) {
if ($a == 50) {
$n = $a;
last;
}
}
# $n is 50
The advantage to new syntax would be that it promotes awareness of the two non-compatible WIMs. It could also have the ever-so-slight advantage of reducing the number of variables declared. I've thought of three possible syntax extensions:
- An alias pragma, on by default:
no alias;
for $n (1..100)
- The addition of an equals sign to indicate that each element is assigned, rather than aliased:
for $n = (1..100)
- Using a ref to a scalar var instead of a scalar var to indicate non-localization:
for \$n (1..100)
None of these would affect existing code (unless there's already an alias module/pragma of which I'm unaware).
The PerlMonk tr/// Advocate