6

質問1:

関数に配列を渡したい。ただし、渡された引数は関数内で変更されます。値によって呼び出されますか?

質問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
4

1 に答える 1

11
関数に配列を渡したい [...] 出力が異なります。なぜそれが起こったのですか?

関数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";

ただし、渡された引数は関数内で変更されます。値によって呼び出されますか?

Perl は決して値渡しをしません。常に参照渡しです。の要素を@_変更すると、呼び出し元の対応する引数が変更されます。

$ 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).

Storableを使用して、配列のdclone「ディープ コピー」を作成できます。

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
于 2012-05-22T16:25:04.970 に答える