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

前端 未结 7 2284
一整个雨季
一整个雨季 2020-12-18 19:58

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 outp

7条回答
  •  一生所求
    2020-12-18 20:03

    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.

提交回复
热议问题