问题一:
我想将数组传递给函数。但是传递的参数在函数中发生了变化。它是按值调用的吗?
问题2:
#my ($name, $num, @array)= @_; <=1 )
my $name = shift; <=2 )
my $num = shift;
my @array = shift;
情况 1 和 2 的输出不同。为什么会发生?
#!/usr/bin/perl
use strict;
my @test1;
push @test1, ['a', 1];
push @test1, ['b', 1];
push @test1, ['c', 1];
push @test1, ['d', 1];
push @test1, ['e', 1];
for (my $i=0; $i< scalar(@test1); $i++) {
print "out1: $test1[$i][0] $test1[$i][1]\n";
}
test_func("test_func", 10, @test1);
sub test_func {
#my ($name, $num, @array)= @_; <=1)
my $name = shift; <=2)
my $num = shift;
my @array = shift;
print "$name\n";
print "$num\n";
for (my $i=0; $i< scalar(@test1); $i++) {
print "$array[$i][0] $array[$i][1]\n";
}
for (my $i=0; $i< scalar(@test1); $i++) {
if ($array[$i][0] eq 'a') {
$array[$i][0] = 'z';
}
}
for (my $i=0; $i< scalar(@test1); $i++) {
print "change: $array[$i][0] $array[$i][1]\n";
}
}
for (my $i=0; $i< scalar(@test1); $i++) {
print "out2: $test1[$i][0] $test1[$i][1]\n";
}
#
下面是测试输出。
out1: a 1
out1: b 1
out1: c 1
out1: d 1
out1: e 1
test_func
10
a 1
b 1
c 1
d 1
e 1
change: z 1
change: b 1
change: c 1
change: d 1
change: e 1
out2: z 1 <= Why did it change?
out2: b 1
out2: c 1
out2: d 1
out2: e 1