my %pair = ( 'foo' => 'bar', 'jack' => 'daniels', 'Tom' => 'Jerry', 'BEGIN' => 'END', ); my %data; my $tail; my $type; while () { chomp; s/\s+$//; # Clean up invisible stuff if ($pair{$_}) { $type = $_; $tail = $pair{$_}; } elsif ($_ eq $tail) { undef $type; } push (@{$data{$type}}, "$_\n"); }