# untested while (<$first_fh>){ chomp; my %infirst; # every word become a key of temporary hash map{$infirst{$_}++} split ' ',$_; my $ref_line = <$second_fh>; chomp $ref_line; print grep {exists $infirst{$_}} split ' ',$ref_line; die "$file_one exhausted!" if eof($first_fh); die "$file_two exhausted!" if eof($second_fh); }