for (my $pos = length($text); $pos ; --$pos) { my $char = substr($text, $pos-1, 1); if ($char =~ /\S/ and (int rand 2)) # 0 or 1 { substr($text, $pos-1, 1) = "$opening_tag$char$closing_tag"; } } #### $text =~ s/(\S)/(int rand 2) ? "$opening_tag$1$closing_tag" : $1/ge; #### my $tag_is_open = 0; for (my $pos = length($text); $pos > 0; ) { my $char = substr($text, -$pos, 1); if ($char =~ /\S/ and (int rand 2)) # 0 or 1 { if ($tag_is_open) { substr($text, -$pos, 1) .= $closing_tag; $pos-=2; # After closing a tag, skip at least one char } else { substr($text, -$pos, 0) = $opening_tag; } $tag_is_open ^= 1; # Toggle } else { --$pos } } $text .= $closing_tag if $tag_is_open;