in reply to Reassigning $_ in loop doesn't stick
Ordinarily if you loop over an array, the loop variable becomes an alias to each element of the array. If you're looping over the results of some other expression, however, you can't always map them to some array element, so the loop variable is actually a copy.
Update: This is totally wrong! I really need to try it before I post it!
For example, in this case, we're filtering the elements of the array. Even though the elements of the original array are passed through unaltered, it doesn't alias them.
foreach my $x ( grep defined, @foo ) { $x = rand; ]
Here's an example where the elements get modified (with map) even before reaching the foreach, so the loop variable can't be an alias to the original values.
foreach my $x ( map "x$_", @foo ) { $x = rand; }
Your example with eval is another example where the expression being looped over won't be aliased to the loop variable.
You can find foreach documented in perlsyn.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Reassigning $_ in loop doesn't stick
by ikegami (Patriarch) on Jan 21, 2009 at 21:09 UTC | |
by Limbic~Region (Chancellor) on Jan 21, 2009 at 21:24 UTC | |
by kyle (Abbot) on Jan 21, 2009 at 21:31 UTC | |
by ikegami (Patriarch) on Jan 21, 2009 at 21:33 UTC | |
by Limbic~Region (Chancellor) on Jan 21, 2009 at 23:58 UTC | |
by ikegami (Patriarch) on Jan 22, 2009 at 05:19 UTC |