2
votes

I have a table like this with 3 columns, called table1

1       2       A
2       3       B
4       5       D

I have another table with one column, called table2, looking like this

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

1    2    A
2    3    B

I'm writing in Perl and think I should do this using hash. So I tried the following

#!/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?

1
Note that there is a Unix command join that you can use to do this. stackoverflow.com/questions/6393333/… Happy perl-ing, though!user1717259

1 Answers

3
votes

You need to use $hash{$keyfield} = 1 to create an association instead of push.

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.