Possible Duplicate:
for loop in perl
use warnings;
my @a = (1, 2, 3, 4, 5);
for $x (@a)
{
print $x*=2;
print "\n";
}
print "outside the loop \n";
print "@a";
Codepad link: http://codepad.org/D2Aa74nZ
Any operation on $x
is changing the contents of the original array. Is $x
behaving like a reference/pointer and not like a variable?
This is documented behavior in "Foreach Loops" in perlsyn. The loop variable is aliased to each element in the list that's being looped over. It's not like a Perl reference, but it's somewhat like a pointer if you consider that every Perl variable is really a pointer that associates a name with a piece of data, and a piece of data can be found by more than one name — for example $x
and $a[0]
— at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With