... my $rxHeader = qr {(?x) (?: (?<=\A) | (?<=\n) ) ([=]{2,}) ([ your big character class ]+) \1 }; ... while ( $post->{ post_message } =~ m{$rxHeader}g ) { my $section = get_section_code( $2 ,$post->{ post_message } ); my @subheaders; while ( $section =~ m{$rxHeader}g ) { push @subheaders, $2; ... } push @headers, { Section => $section, SubLoop => \@subheaders } }