in reply to Modify array elements inside for loops
Now, your post seems a little ambiguous (to my eyes), but if you are looking for a shorter way to directly modify array elements (not copies), then:
my @array = (1,2,3); $_ *= 2 for @array; print "@array\n"; # prints: 2 4 6
This works because the loop variable is aliased to each lvalue in the list in turn. This also means that such code will throw an exception if any of the elements in the list are not lvalues and you try to modify them:
$_ *= 2 for 1,2,3; # error: modification of read-only value
Now, if you actually meant you want to muck about without changing the actual array itself, then copying the loop variable inside the loop is one easy way. Another possibility is to generate the list via map():
my @array = (1,2,3); for my $e (map $_, @array) { $e++; # or whatever } print "@array\n";
However, this builds a new list and iterates over it, so it would be more efficient (memory-wise) to just make a copy of each item inside the loop as you did (at least for largish arrays).
|
|---|