http://www.perlmonks.org?node_id=72632


in reply to NEWBIE Brain Teaser

First of all: ++ nysus and kudra for promoting learning
Since nobody posted the reason why it does this I figured I'd do so. In fact, instead of waste my time, I just took this from "Learning Perl" written by Randal Schwartz, Published by OReilly Associates.

If the list you are iterating over is made of real variables rather than some function returning a list value, then the variable being used for iteration is in fact an alias for each variable in the list instead of being merely a copy of the values. It means that if you change the scalar variable, you are also changing that particular element in the list that the variable is standing in for. For example:

@a = (3,5,7,9);
foreach $one (@a) {
$one *= 3;
}
# @a is now (9,15,21,27)

Notice how altering $one in fact altered each element of @a. This is a feature, not a bug.


Macphisto the I.T. Ninja

Everyone has their demons....