my $c_file = "NO MATCH"; while (<$hfile>) { my $line = $_; if ($line =~ /[DWEM]\s+.*?\s+(?:c|cm|M)\:($input_pid)\s+([^\.]+\.c+)/s) { $c_file = $2; my $pid = $1; } if($input_string eq $c_file) { #check with input string print $ofile "$line\n"; #write the output in a output file } }