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

前端 未结 7 2282
一整个雨季
一整个雨季 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:24

    $a in this case is an alias to the array element. Just don't have $a = in your code and you won't modify the array. :-)

    If I remember correctly, map, grep, etc. all have the same aliasing behaviour.

提交回复
热议问题