【问题标题】:perl compare files using hashes with multiple keysperl 使用带有多个键的哈希比较文件
【发布时间】:2014-11-07 09:51:58
【问题描述】:

我有以下脚本,我使用哈希比较两个文件中的列。

但是当 $conversion 中的 cols[5] 和 $table 中的 cols[2] 匹配时,我想打印出 $conversion 中另一列的值,即 cols[1] 中的对应值。我试图通过将 cols[1] 中的值分配给我的 %hash 中的第二个键,称为 $keyfield2 来做到这一点。但我没有成功打印它。到目前为止,这是我的代码:

my %hash = ();
while(<$conversion>){
    chomp;
    my @cols = split(/\t/);
    my $keyfield = $cols[5];
    my $keyfield2 = $cols[1];
    $hash{$keyfield,$keyfield2}++;
    }
seek $table,0,0; #cursor resetting
while(<$table>){
    my @cols = split(/\t/); 
    my $keyfield = $cols[2]; 
    if (exists($hash{$keyfield})){
        print $output "$cols[0]","\t","$hash{$keyfield2}","\t","$cols[1]\n";
    }
}

关于如何做到这一点的任何提示?

【问题讨论】:

    标签: perl hash


    【解决方案1】:

    您使用哈希引用是否有原因。用哈希试试这个:

    my $keyfield = $cols[5];
    my $keyfield2 = $cols[1];
    $hash{$keyfield} = $keyfield2
    

    然后打印到:

    print $output "$cols[0]","\t","$hash{$keyfield}","\t","$cols[1]\n";
    

    【讨论】:

    • col 在第二个循环中被覆盖。所以在打印中,col 是表中的值。只需使用 $keyfield2 从转换中获取 col1 的值。
    猜你喜欢
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    相关资源
    最近更新 更多