定义哈希值和键以及使用多个不同的文件

时间:2013-03-16 20:16:39

标签: perl hash multidimensional-array

我正在努力为多个任务编写Perl程序。我已经非常努力地审查所有错误,因为我是初学者并想要理解我的错误,但我失败了。希望到目前为止,我对任务和我的缺陷程序的描述不会令人困惑。

在我当前的目录中,我有一个可变数量的“.txt。”文件。 (我可以有4个,5个,8个或任意数量的文件。但是,我认为我不会得到更多的17个文件。)“。txt”文件的格式是相同的。有六列,由空格分隔。我只关心这些文件中的两列:第二列,即珊瑚礁regionID(由字母和数字组成),第五列是p值。每个文件中的行数未确定。我需要做的是找到所有.txt文件中的所有常见regionID,并将这些公共区域打印到outfile。但是,在打印之前,我必须对它们进行排序。

以下是我的程序到目前为止,但我收到了错误消息,我在程序之后包含了这些消息。因此,我对变量的定义是主要问题。我非常感谢您撰写该计划的任何建议,并感谢您对像我这样的初学者的耐心。

更新:我已按照建议声明变量。查看我的程序后,会出现两个语法错误。

   syntax error at oreg.pl line 19, near "$hash{"
   syntax error at oreg.pl line 23, near "}"
   Execution of oreg.pl aborted due to compilation errors.

以下是已编辑程序的摘录,其中包含所述错误的位置。

#!/user/bin/perl
use strict;
use warnings;
# Trying to read files in @txtfiles for reading into hash
foreach my $file (@txtfiles) {
  open(FH,"<$file") or die "Can't open $file\n";
  while(chomp(my $line = <FH>)){
    $line =~ s/^\s+//;      
    my @IDp = split(/\s+/, $line); # removing whitespace
    my $i = 0;
    # trying to define values and keys in terms of array elements in IDp
    my $value = my $hash{$IDp[$i][1]};
    $value .= "$IDp[$i][4]"; # confused here at format to append p-values
    $i++;       
  }                         
}

close(FH);

这些是过去的错误:

Global symbol "$file" requires explicit package name at oreg.pl line 13.
Global symbol "$line" requires explicit package name at oreg.pl line 16.
#[And many more just like that...]
Execution of oreg.pl aborted due to compilation errors.

2 个答案:

答案 0 :(得分:2)

您没有声明$file

foreach my $file (@txtfiles) {

您没有声明$line

while(chomp(my $line = <FH>)){

答案 1 :(得分:0)

use strict;
use warnings;

my %region;
foreach my $file (@txtfiles) {
  open my $FH, "<", $file or die "Can't open $file \n";
  while (my $line = <$FH>) {
    chomp($line);
    my @values = split /\s+/, $line;
    my $regionID = $values[1]; # 2nd column, per your notes
    my $pvalue = $values[4]; # 5th column, per your notes
    $region{$regionID} //= []; # Inits this value in the hash to an empty arrayref if undefined
    push @{$region{$regionID}}, $pvalue;
  }                         
}
# Now sort and print using %region as needed

在此代码的末尾,%region是一个哈希,其中键是区域ID,值是包含各种p值的数组引用。

这里有一些片段可以帮助您完成后续步骤:

keys %regions会为您提供区域ID值列表。

my @pvals = @{$regions{SomeRegionID}}会为您提供SomeRegionID

的pvalue列表

$regions{SomeRegionID}->[0]将为您提供该地区的第一个pvalue。

您可能想要查看Data :: Printer或Data :: Dumper - 它们是CPAN模块,可以让您轻松打印出您的数据结构,这可以帮助您了解代码中发生了什么。