syllogismos
syllogismos

Reputation: 660

for loop in perl

my @array=(1..10);
for my $i (@array){$i++;}
print "array is now:@array";

this is changing the values of the array. Why?

Upvotes: 2

Views: 1018

Answers (4)

Nathan Fellman
Nathan Fellman

Reputation: 127608

The loop variable $i is aliased to each element in the array in turn.

That means that if you change $i you're changing the array.

Upvotes: 1

Eugene Yarmash
Eugene Yarmash

Reputation: 150138

This is documented behaviour. See perldoc perlsyn:

The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn.

If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.

Upvotes: 3

parent5446
parent5446

Reputation: 898

I believe it is because in perl when you loop through an array, each element is passed by reference, meaning when you change $i in the loop, it is changing the actual value in the array. I'm not sure how to make it pass by value, though.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994649

This is what the for statement in Perl is defined to do. See the documentation for Foreach Loops in man perlsyn:

If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.

Upvotes: 6

Related Questions