在mytest.pl的子例程条目中使用未初始化的值

时间:2013-05-07 14:02:34

标签: perl perl-module perl-data-structures

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw(min max);
use Set::IntervalTree;
use GenomeLookupUtil;

my $chromCol = 0;
my $startCol = 0;
my $endCol   = 0;
if($ARGV[2] eq "VSC") {
    $chromCol = 0;
    $startCol = 1;
    $endCol   = 2;
} else {
    $chromCol = 1;
    $startCol = 2;
    $endCol   = 3;
}

open (IN2,"$ARGV[0]") || die "counldn't open";
print STDERR "Read mask file \n";
my @masklines   = ();
my $i           = 0;
my %mask_hash   = ();
my $current_chr = '01';
my $current_snp_ranges = Set::IntervalTree->new();
while (<IN2>){
    my @masklines = split ("\t", $_);
    if ($masklines[1] ne $current_chr) {
            $mask_hash{$current_chr} = $current_snp_ranges;
            $current_snp_ranges = Set::IntervalTree->new();
    }

    $current_chr = $masklines[$chromCol];
    $current_snp_ranges->insert(
        [ $masklines[$startCol], $masklines[$endCol] ],
          $masklines[$startCol], 
          $masklines[$endCol]
    );
}
$mask_hash{$current_chr} = $current_snp_ranges;
close (IN2);

当我运行带有不必要参数的代码时,该文件显示错误为

Use of uninitialized value in subroutine entry at mytest.pl line 47, <IN2> line 100.

我初始化了所有变量,并且我的代码中也没有使用任何子程序。第47行是

$current_snp_ranges->insert(
      [ $masklines[$startCol], $masklines[$endCol] ],
        $masklines[$startCol], 
        $masklines[$endCol]
);

1 个答案:

答案 0 :(得分:2)

mytest.pl第47行,第100行的子程序条目中的未初始化值表明前99行输入数据正常。那么输入数据的第100行是什么?它可能是一个空行,可能在文件的末尾吗?

代码早期有my @masklines=split ("\t",$_);,但没有检查数组是否收到足够的数据来支持第47行尝试从数组中提取值。也许第100行的制表符分隔字段少于预期。

我建议在my @masklines=split ("\t",$_);之后添加类似于:

的代码
if ( $#masklines < $endCol ) {
    print "Too few fields in line: $_";
}
else {
    ... the rest of the code within the while statement
}

更新: 问题的措辞是建议只有一行给出错误。但是,没有检查分割是否提取了所需的字段数。编写用于检查错误输入数据的防御性代码是一种很好的做法。为了帮助找到问题,您可以尝试在第47行之前添加一系列打印语句,例如:

print "startcol $startCol\n";
print "endcol $endCol\n";
print "masklines-startCol $masklines[$startCol]\n";
print "masklines-endCol $masklines[$endCol]\n";

使它们成为单独的行将在更简单的行上提供未初始化的变量,以帮助理解问题的根源。