gpt4 book ai didi

arrays - 如何在Perl中将数组传递给函数?

转载 作者:行者123 更新时间:2023-12-04 13:53:05 25 4
gpt4 key购买 nike

问题1:

我想将数组传递给函数。但是,传递的参数在函数中已更改。是按值(value)来称呼的吗?

问题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

最佳答案

I want to pass an array to a function [...] has different output. Why did it occur?


您不能将数组传递给function子函数。 Sub只能将标量列表作为参数。
test_func("test_func", 10, @test1);

是相同的
test_func("test_func", 10, $test1[0], $test1[1], $test1[2], $test1[3], $test1[4]);

在执行操作时,您将在 test_func中创建一个新数组
my ($name, $num, @array) = @_;
shift返回 @_的第一个元素,该元素必须是标量。 @_是一个数组,并且数组的元素是标量。等效为
my $name  = shift(@_);
my $num = shift(@_);
my @array = splice(@_);

要将数组传递给子数组,通常会将一个引用传递给它。
test_func("test_func", 10, \@test1);

my ($name, $num, $array) = @_;

my $name = shift;
my $num = shift;
my $array = shift;

say "@$array";

But the passed argument is changed in the function. Is it called by value?


Perl永远不会超越值(value)。它总是通过引用传递。如果更改 @_的任何元素,它将更改调用方中的相应参数。
$ perl -E'sub f { $_[0] = "def"; }  my $x = "abc"; f($x); say $x;'
def

但这不是问题。您无需更改 @_的任何元素。您正在做的是更改 $test[0]$array[0]引用的单个数组。

这是您在做什么:
my $ref1 = [ 'a', 1 ];  # aka $test1[0]
my $ref2 = $ref1; # aka $array[0]
$ref2->[0] = 'z'; # Changes the single array (not $ref1 or $ref2).

这是短的
my @anon = ( 'a', 1 );
my $ref1 = \@anon; # aka $test1[0]
my $ref2 = $ref1; # aka $array[0]
$ref2->[0] = 'z'; # Changes @anon (not $ref1 or $ref2).

Storabledclone可用于制作数组的“深拷贝”。
my $ref1 = [ 'a', 1 ];
my $ref2 = dclone($ref1); # clones the reference, the array, 'a' and 1.
$ref1->[0] = 'y'; # Changes the original array
$ref2->[0] = 'z'; # Changes the new array

关于arrays - 如何在Perl中将数组传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10705728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com