For a loop in Perl

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 in $x changes the contents of the original array. Is $x behaving like a link / pointer and not like a variable?

+4
source share
2 answers

This is documented behavior in "Foreach Loops" in perlsyn . A loop variable is an alias for every element in the list that loops. It doesn't look like a Perl link, but it looks a bit like a pointer if you think that each 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.

+11
source

Yes, a loop variable is an alias for the contents of a looped array and can be used to change it. This allows you to do things like $_ += 1 for @numbers; .

This feature is documented in perldoc perlsyn in the "Loop Cycles" section.

+3
source

All Articles