OK, I have the following code:
use strict;
my @ar = (1, 2, 3);
foreach my $a (@ar)
{
$a = $a + 1;
}
print join ", ", @ar;
and the output?
2, 3, 4
What the heck? Why does it do that? Will this always happen? is $a not really a local variable? What where they thinking?
Perl has lots of these almost-odd syntax things which greatly simplify common tasks (like iterating over a list and changing the contents in some way), but can trip you up if you’re not aware of them.
$ais aliased to the value in the array – this allows you to modify the array inside the loop. If you don’t want to do that, don’t modify$a.