for my $file ( qw/path_n path_p/ ) { open PATH, $file or die "$file: $!"; while () { # use a regex match with parens to capture path string in $1 # and test to see if the path string was in dif_file: if ( /^(\S+)/ and exists( $diff_hash{$1} )) { print; # or whatever else you need to do with this record } } close PATH; }