my $section = ''; foreach (@m) { if ( /^ #match the start of the line \s* #match 0 or more whitespace characters grab as many as we can ( #start captureing [\w\s]*? #match 0 or more word or whitespace, grab as _few_ as posible ) #end capture \s* #match 0 or more whitespace characters : #until we reach the a colon /x #x added for the comments && #if the match fails we don't bother checking $1 $1) { #check if we captured any thing if there was only whitespace before the colon we won't have captured any thing $section = $1; #if we actualy found a section label save it } #$section should now be set to the last section label we found. if ($section eq '...') { ... }