use strict; use warnings; my %headers; while (<>) { $headers{$1} = 1 if /^>(.+)/; last if eof; } local $/ = 'Query= '; while (<>) { chomp; print $/. $_ if /(.+)/ and defined $headers{$1}; }