Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop in Perl [duplicate]

Tags:

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 on $x is changing the contents of the original array. Is $x behaving like a reference/pointer and not like a variable?

like image 238
Chankey Pathak Avatar asked Dec 10 '22 07:12

Chankey Pathak


1 Answers

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.

like image 138
hobbs Avatar answered Jan 14 '23 00:01

hobbs