[英]Perl: How to pass a 2-dimensional array to a subroutine?
我正在嘗試將二維數組傳遞給子例程並返回一個新數組。 在子例程內部創建了一個新變量,但是在調用該子例程之后,初始數組會有所更改。 同時,一維數組不存在此類問題。
這是代碼:
#!/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
,並且其值會更改。
您做了@empty_profile
的淺表副本,但是由於它的每個元素都是數組引用,因此@empty_profile
對其進行復制,因此原始值不會更改,
my @p = map [ @$_ ], @{$_[1]};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.