%Marks = ( STARTPRESERVE => 'STOPPRESERVE', BEGIN => 'END' ); $MarkOptions = join("|",keys %Marks); $text =~ s/ \s+ | # spaces, or: ( # begin $1 ($MarkOptions)(\d?) # $2=START + $3=optional_number .*? # anything $Mark{\2}\3 # $Mark{START} + optional_number ) # end $1 /${ [$1,' '] }[ ! $1 ]/sgx; # [$1,' '] is an unnamed array. # ! $1 is: # 0 if $1 exists; # 1 if spaces were found.