my @section; my $i = -1; foreach (split /\n/, $str) { if (/^===Comments===$/) { ++$i; next; } next unless $i >= 0; $section[$i] .= "$_\n"; }