Perl:子例程中的更改不在例程之外打印

时间:2014-07-02 23:08:55

标签: perl reference argument-passing subroutine

所以我想改变我传递给子程序的数字,然后保留那些被改变的数字,但它似乎不起作用。

    my $A = 0;
    my $T = 0;
    my $C = 0;
    my $G = 0;   

     foreach my $bases in (keys %basereads){
          count ($bases, $A, $T, $C, $G);
    }

这是我的子程序

    sub count {
    my $bases = shift;
    my $A = shift;
    my $T = shift;
    my $C = shift;
    my $G = shift;
            for (my $i = 0; $i < length($bases); $i++){
                    print "$bases\t";
                 if (uc(substr($bases,$i,1)) eq 'A'){
                               $A++;
                 }elsif (uc(substr($bases,$i,1)) eq 'T'){
                               $T++;
                 } elsif (uc(substr($bases,$i,1)) eq 'G'){
                               $G++;
                 } elsif (uc(substr($bases,$i,1)) eq 'C'){
                                $C++;
                 } else { next; }

           }
            print "$A\t$C\t$T\t$G\n";
    return my($bases, $A, $T, $C, $G);

    }

在子程序之后,我想将改变后的A,C,T,G存储到一个hashmap中。当我在子程序中打印底座和ATCG时,它打印出来,所以我知道计算机正在运行子程序,但它没有保存它,当我试图在子程序之外操作它(在我调用之后),它从零开始(我之前定义了四个基地)。我是Perl的新手,所以我对子程序有点厌倦。     有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

始终在每个脚本的顶部加入use strict;use warnings;

启用warnings后,您应该收到以下消息:

"my" variable $bases masks earlier declaration in same scope at script.pl line ...
"my" variable $A masks earlier declaration in same scope at script.pl line ...
"my" variable $T masks earlier declaration in same scope at script.pl line ...
"my" variable $C masks earlier declaration in same scope at script.pl line ...
"my" variable $G masks earlier declaration in same scope at script.pl line ...

这些是由my声明之前的return引起的:

return my($bases, $A, $T, $C, $G);

只需删除my

即可解决此问题
return ($bases, $A, $T, $C, $G);

然后你只需要捕获你的返回值

($bases, $A, $T, $C, $G) = count($bases, $A, $T, $C, $G);

鉴于您是perl的新手,我相信您的代码可以进一步清理后不会感到惊讶。如果使用散列,则可以更轻松地计算字符串中的各种字符,如下所示:

use strict;
use warnings;

my $A = 0;
my $T = 0;
my $C = 0;
my $G = 0;   

foreach my $bases (keys %basereads) {
    my %counts;
    for my $char (split //, $bases) {
        $counts{$char}++;
    }
    $A += $counts{A};
    $T += $counts{T};
    $C += $counts{C};
    $G += $counts{G};
}