... while (<$stdout_fh>) { chomp; if (/Have a nice day!\z/) { print("$query\n"); } elsif ($answers{$query}) { print($stdin_fh "$answers{$query}\n"); } else { # ...[ Do something with unrecognised output from STDIN. ]... } }