简体   繁体   English

perl使用带有多个键的哈希比较文件

[英]perl compare files using hashes with multiple keys

I have the following script with which I compare columns from two files using a hash. 我有以下脚本,可以使用哈希比较两个文件中的列。

But when there is a match between cols[5] from $conversion and cols[2] from $table, I want to print out the value from another column in $conversion, namely the corresponding value in cols[1]. 但是,当$ conversion的cols [5]和$ table的cols [2]之间存在匹配项时,我想从$ conversion的另一列中打印出值,即cols [1]中的相应值。 I've tried to do this by assigning the value from cols[1] to a second key in my %hash, called $keyfield2. 我试图通过将cols [1]中的值分配给我的%hash中的第二个键(称为$ keyfield2)来完成此操作。 But I don't succeed in printing it. 但是我没有成功打印它。 This is my code so far: 到目前为止,这是我的代码:

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";
    }
}

Any hints on how to do this? 关于如何执行此操作的任何提示?

Is there a reason you use a hash reference. 使用散列引用是否有原因? With a hash try this: 使用哈希尝试:

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

and the print to: 并将打印到:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM