my %ref; open( R, "<", $datafile_name ); while () { if ( /^([^\t]+)/ ) { $ref{$1} = undef; } } my $dbh = DBI->connect( ... ); my $sth = $dbh->prepare( "select m.code, ... from ... where i.name=m.code"); $sth->execute; my $rows = $sth->fetchall_arrayref; for my $r ( @$rows ) { my ( $mcode, ... ) = @$r; next unless exists( $ref{$mcode} ); # do something ... }