Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Perl foreach variable assignment modifying the values in the array?

Tags:

OK, I have the following code:

use strict;
my @ar = (1, 2, 3);
foreach my $a (@ar)
{
  $a = $a + 1;
}

print join ", ", @ar;

and the output?

2, 3, 4

What the heck? Why does it do that? Will this always happen? is $a not really a local variable? What where they thinking?

like image 518
tster Avatar asked Jan 13 '10 20:01

tster


People also ask

How does foreach loop work in Perl?

A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range.

How do I declare an array in Perl?

To refer a single element of Perl array, variable name will be preceded with dollar ($) sign followed by index of element in the square bracket. Syntax: @arrayName = (element1, element2, element3..);


2 Answers

Perl has lots of these almost-odd syntax things which greatly simplify common tasks (like iterating over a list and changing the contents in some way), but can trip you up if you're not aware of them.

$a is aliased to the value in the array - this allows you to modify the array inside the loop. If you don't want to do that, don't modify $a.

like image 57
Anon. Avatar answered Oct 13 '22 00:10

Anon.


See perldoc 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.

There is nothing weird or odd about a documented language feature although I do find it odd how many people refuse check the docs upon encountering behavior they do not understand.

like image 22
Sinan Ünür Avatar answered Oct 13 '22 01:10

Sinan Ünür