简体   繁体   中英

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对其进行复制,因此原始值不会更改,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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