简体   繁体   English

Perl:如何将二维数组传递给子例程?

[英]Perl: How to pass a 2-dimensional array to a subroutine?

I'm trying to pass a 2-dimensional array to a subroutine and return a new array. 我正在尝试将二维数组传递给子例程并返回一个新数组。 A new variable is created inside the subroutine, but somehow the initial array is changed after the subroutine is called. 在子例程内部创建了一个新变量,但是在调用该子例程之后,初始数组会有所更改。 At the same time, there are no problems of such type with 1-dimensional arrays. 同时,一维数组不存在此类问题。

Here is the code: 这是代码:

#!/usr/bin/perl -w
use strict;

my @motifs=('1230','1011','2121');
my @empty_profile;

for (my $i=0;$i<4;$i++) {
    for (my $j=0;$j<4;$j++) {
        $empty_profile[$i][$j]=1/8;
    }
}

for (my $i=0;$i<4;$i++) {
    for (my $j=0;$j<4;$j++) {
        print("$empty_profile[$i][$j] ");
    }
    print "\n";
}

my @new_profile=profile(\@motifs,\@empty_profile);

print("print it again\n");

for (my $i=0;$i<4;$i++) {
    for (my $j=0;$j<4;$j++) {
        print("$empty_profile[$i][$j] ");
    }
    print "\n";
}

sub profile {
    my @motifs=@{$_[0]};
    my @p=@{$_[1]};

    for (my $i=0; $i<4;$i++) {
        for (my $j=0;$j<3;$j++) {
            my $l=substr($motifs[$j],$i,1);
            $p[$l][$i]+=1/8;
        }
    }
    @p;
}

It prints @empty_profile 2 times - before and after the subroutine call - and its values are changed. 在子例程调用之前和之后,它将打印@empty_profile ,并且其值会更改。

您做了@empty_profile的浅表副本,但是由于它的每个元素都是数组引用,因此@empty_profile对其进行复制,因此原始值不会更改,

my @p = map [ @$_ ], @{$_[1]};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM