I have a table like this with 3 columns, called table1
我有一个这样的表有3列,称为table1
1 2 A
2 3 B
4 5 D
I have another table with one column, called table2, looking like this
我有另一个表,有一列,名为table2,看起来像这样
A
B
E
F
If there is a match between table2 and third column of table1, I want to print the matching line as it is to a new table called output, which in this case should look like this
如果table2和table1的第三列之间存在匹配,我想将匹配的行原样打印到名为output的新表中,在这种情况下应该看起来像这样
1 2 A
2 3 B
I'm writing in Perl and think I should do this using hash. So I tried the following
我正在用Perl编写,并认为我应该使用哈希来做这件事。所以我尝试了以下内容
#!/usr/bin/perl
use strict;
use warnings;
open(my $table1,'<',"table1.txt");
open(my $table2,'<',"table2.txt");
open(my $output,'+>',"output.txt");
my %hash = ();
while (<$table2>){
chomp;
my $keyfield = $_;
push @{$hash{keyfield}};
}
seek $table1,0,0;
while (<$table1>){
chomp;
my @cols = split(/\t/);
my $keyfield = $cols[2];
if (exists($hash{$keyfield})) {
print $output $_, "\n";
}
}
This approach worked before, however now I had to modify it slightly. I get the warning: useless use of push with no values at line13 (which is the line where my push is). And my output is empty. What am I doing wrong?
这种方法以前有效,但现在我不得不稍微修改它。我收到警告:在第13行没有使用push的无用(这是我推送的行)。我的输出是空的。我究竟做错了什么?
1 个解决方案
#1
You need to use $hash{$keyfield} = 1
to create an association instead of push
.
您需要使用$ hash {$ keyfield} = 1来创建关联而不是推送。
Per tip from @Sobrique, you can also use $hash{$keyfield}++
which will let you determine later whether key exists and also give you a number of occurrences.
来自@Sobrique的提示,你也可以使用$ hash {$ keyfield} ++,这将让你以后确定密钥是否存在,并且还会给你一些事件。
#1
You need to use $hash{$keyfield} = 1
to create an association instead of push
.
您需要使用$ hash {$ keyfield} = 1来创建关联而不是推送。
Per tip from @Sobrique, you can also use $hash{$keyfield}++
which will let you determine later whether key exists and also give you a number of occurrences.
来自@Sobrique的提示,你也可以使用$ hash {$ keyfield} ++,这将让你以后确定密钥是否存在,并且还会给你一些事件。