2012-10-08 142 views
0

我正在读取文件。我想要一个散列,它给出了一行的第一个数字,作为将其余行的所有数字散列为1的关键字。哈希输出的Perl哈希

我相信我正确地添加了散列,因为Dumper正确打印。 但是,打印“$ first $ secondID \ n”不会给我任何输出。

while (<FILE>) { 

    chomp $_; 

    if (/(\d+)\t(.+)/) { 

     $firstNum = $1; 
     @seconds = split(/\,/,$2); 

     foreach $following (@seconds) { 

      $Pairs->{$firstNum}{$following} = 1; 
     } 

     foreach $first (sort {$a <=> $b} keys %Pairs) { 

      print "$first\n"; 
      %second = {$Pairs{$first}}; 

      foreach $secondID (sort {$a <=> $b} keys %second) { 

       print "$first $secondID\n"; 
      } 
     } 
     print Dumper($Pairs); 
    } 
    else { 

     print "ERROR\n"; 
    } 
} 

后来,由于一对数字我想抬头,看到被定义是否$对{$ NUM1} {$ NUM2}。我会写

if(defined $Pairs{$num1}{$num2}) 

或者我应该先检查第一个键。然后检查第二个关键

+0

'%第二= {对{$第一}};'看起来像一个错字:无印记前'对' – toolic

+0

抱歉意外删除时发布。我正在改变变量的名字。问题依旧。 – user1645240

回答

0

你有几个错误。首先,您似乎不确定您是使用%Pairs还是$Pairs来存储您的散列,其次您有%second = {$Pairs{$first}},它会尝试将散列引用分配给散列%second。想必你想my %second = %{ $Pairs{$first} }

你应该使用my总是use strictuse warnings在所有Perl程序的启动,并宣布在第一次使用的时候所有的变量。这会提醒您简单的错误,否则您可能会轻易忽略这些错误,并且会显示您在此程序中使用了%Pairs$Pairs,以及您尝试将单个值(哈希引用)分配给哈希值。

与其复制整个散列,您应该在$seconds中保存对它的引用。然后,您可以在以下for循环中对其进行解引用。

有经验的Perl程序员也会感谢你为本地变量使用小写加下划线,并为包和类名保留大写字母。

此程序可以为你打算,并希望将文件名作为命令行参数:

use strict; 
use warnings; 

my %pairs; 

while (<>) { 

    unless (/(\d+)\s+(.+)/) { 
    print "ERROR\n"; 
    next; 
    } 

    my $first_num = $1; 
    my @seconds = split /,/, $2; 

    foreach my $following (@seconds) { 
    $pairs{$first_num}{$following} = 1; 
    } 

    foreach my $first (sort { $a <=> $b } keys %pairs) { 
    print "$first\n"; 
    my $second = $pairs{$first}; 
    foreach my $second_id (sort { $a <=> $b } keys %$second) { 
     print "$first $second_id\n"; 
    } 
    } 

} 
0
my %hash; 
while (<>) { 
    my @numbers = split /\D+/; 
    my $key  = shift @numbers; 
    @{$hash{$key}}{ @numbers } = (1) x @numbers; 
} 


# test it this way... 
if ($hash{ $num1 }{ $num2 }) { 

} 
0

用途:

%second = %{$Pairs->{$first}};