use strict; my %B_rids; # ... open file B, read it to fill %B_rids hash, then: my @A_files = ... # do something to get list of A file paths/names for my $A_file ( @A_files ) { unless ( open( my $afh, "<", $A_file )) { # update: you'll add encoding on 2nd arg, e.g. "<:utf8" warn "Open failed for $A_file: $!\n"; next; } while (<$afh>) { chomp; my @fields = split /\t/; if ( exists( $B_rids{ $fields[4] } )) { # does rid1 exist in B? # do something } elsif ( exists( $B_rids{ $fields[5] } )) { # does rid2 exist in B? # do something else } } }