foreach $line ( ) { if ( $line !~ /to=<.*(our\.domain)/i) { # our external domain is a subset of the ones we're looking for if ($line =~ /to=<.*\.gov>.*relay=localhost/i) { @ids = ($line =~ /\ ([0-9A-F]{11,12})/g); %msgids{$ids[0]} = $ids[1]; } } } open (FH2, $file ) or die "Cannot open file 2nd time: $!"; foreach $line ( ) { if ( $line !~ /client=(ourhost1|ourhost2)/ ) { foreach $keys (%msgids) { if ($key =~ /$line/) { delete $msgids $key; } } } # then do something to run through the log again and print # the delivery report line from the second msgid