my $section = ''; foreach (@m) { if (/^\s*([\w\s]*?)\s*:/ && $1) { #if we matched and we captured a section label $section = $1; } if ($section eq '...') { ... }