【问题标题】:Perl: How to pass a 2-dimensional array to a subroutine?Perl:如何将二维数组传递给子程序?
【发布时间】:2014-11-18 20:49:16
【问题描述】:

我正在尝试将二维数组传递给子例程并返回一个新数组。在子例程中创建了一个新变量,但在调用子例程后初始数组发生了某种变化。同时,这种类型的一维数组也不存在问题。

代码如下:

#!/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;
}

它打印@empty_profile 2 次 - 在子例程调用之前和之后 - 并且它的值被更改。

【问题讨论】:

    标签: arrays perl reference


    【解决方案1】:

    您对@empty_profile 做了一个浅拷贝,但由于它的每个元素都是数组引用,所以也要复制它们,这样原始值就不会被改变,

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

    【讨论】:

    猜你喜欢
    • 2017-04-20
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多