In a foreach $var (@list)
construct, $var
becomes aliased to the elements of the loop, in the sense that the memory address of $var
would be the same address as an element of @list
. So your example code attempts to modify read-only values, and you get the error message.
This little script will demonstrate what is going on in the foreach
construct:
my @a = (0,1,2);
print "Before: @a\n";
foreach my $var (@a) {
$var += 2;
}
print "After: @a\n";
Before: 0 1 2
After: 2 3 4
Additional info: This item from perlsyn
is easy to gloss over but gives the whole scoop:
Foreach loops
...
If any element of LIST is an lvalue,
you can modify it by modifying VAR
inside the loop. Conversely, if any
element of LIST is NOT an lvalue, any
attempt to modify that element will
fail. In other words, the "foreach"
loop index variable is an implicit
alias for each item in the list that
you're looping over.