I once needed to word wrap a string that had embedded HTMLish color tags, like: "press <red>X<grey> for status" Text::Wrap considered the <red> and <grey> bits as part of the string, but they would really later be converted to escape codes. With no way to tell Text::Wrap to consider certain parts of the string as having zero-width, I rolled my own useful word wrap routine that can disregard parts of the string, yet leave them in the right places.
sub wrap { my $width = shift; my @msgs; foreach my $in (@_) { my $realline = ""; my $line = ""; # Leading whitespace SHOULD be preserved!!! my $lead; if ($in =~ s/^(\s+)//) { $realline .= $1; $line .= $1; $lead = 1; } else { $lead = 0; } # My homegrown word wrap that disregards <color> tags! foreach my $realword (split(/\s/, $in)) { # Strip the word first. my $word = $realword; $word =~ s/<[^>]+>//g; if (length($line) + length($word) + 1 <= $width) { $word = " $word" unless length($line) == 0 or $lead; $realword = " $realword" unless length($realline) == 0 or $lea +d; $line .= $word; $realline .= $realword; } else { push @msgs, $realline; $line = $word; $realline = $realword; } $lead = 0; } # Leftovers! push @msgs, $realline; } return @msgs; }