0

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

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

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

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

   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.
4

2 回答 2

2

你没有申报$file

foreach my $file (@txtfiles) {

你没有申报$line

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

等等

于 2013-03-16T20:24:22.847 回答
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,值是包含各种 pvalue 的数组引用。

以下是一些可以帮助您完成后续步骤的片段:

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

my @pvals = @{$regions{SomeRegionID}}将为您提供 SomeRegionID 的 pvalues 列表

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

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

于 2013-03-22T15:51:43.543 回答