其實在這個例子中有一個很好的理由使用my
。
您實際上希望每次通過子例程時都重新創建該變量,否則您將更改之前獲得的值。
use strict;
use warnings;
use 5.10.1;
my @array;
sub A{
push @array, scalar @array; # add the length of @array to the end
return \@array;
}
my @list;
for('A'..'D'){
my $current = A();
push @list, $current;
say join ' ', @$current;
}
say '';
say join ' ', @$_ for @list;
0
0 1
0 1 2
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3
通知@array
每個副本怎麼是相同的。
這就是爲什麼每次調用子程序時都需要一個新的副本。
use strict;
use warnings;
use 5.10.1;
sub A{
state $iter = 0;
my @array;
push @array, 0..$iter++;
return \@array;
}
my @list;
for('A'..'D'){
my $current = A();
push @list, $current;
say join ' ', @$current;
}
say '';
say join ' ', @$_ for @list;
0
0 1
0 1 2
0 1 2 3
0
0 1
0 1 2
0 1 2 3