$text =~ s/ [ ]+ | # spaces, or: ( # begin $1 STARTPRESERVE(\d?) # STARTPRESERVE + $2 .*? # anything STOPPRESERVE\2 # STOPPRESERVE + $2 ) # end $1 /${ [$1,' '] }[ ! $1 ]/sgx; # [$1,' '] is an unnamed array. # ! $1 is: # 0 if $1 exists; # 1 if spaces were found.