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

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

    the important distinction here is that when you declare a my variable in the initialization section of a for loop, it seems to share some properties of both locals and lexicals (someone with more knowledge of the internals care to clarify?)

    my @src = 1 .. 10;
    
    for my $x (@src) {
        # $x is an alias to elements of @src
    }
    
    for (@src) {
        my $x = $_;
        # $_ is an alias but $x is not an alias
    }
    

    the interesting side effect of this is that in the first case, a sub{} defined within the for loop is a closure around whatever element of the list $x was aliased to. knowing this, it is possible (although a bit odd) to close around an aliased value which could even be a global, which I don't think is possible with any other construct.

    our @global = 1 .. 10;
    my @subs;
    for my $x (@global) { 
        push @subs, sub {++$x}
    }
    
    $subs[5](); # modifies the @global array
    
    0 讨论(0)
提交回复
热议问题