in reply to RFC: Is there a better way to use Text::Balanced?

Hi Aleena,

No idea if this is cookie worthy, but you got me interested in looking at the Text::Balanced module:

use Text::Balanced qw(extract_multiple gen_extract_tagged); my $codes = qr(A|ABBR|ACRONYM|B|BIG|CITE|CODE|DFN|EM|I|KBD|SAMP|SMALL| +SPAN|STRONG|SUB|SUP|TT|VAR); my $extractor = [ gen_extract_tagged('<!--', '-->', ''), gen_extract_tagged("$codes<", '>', '') ]; # Join all plain text segments, and element substitutions; removing co +mments sub inline { my $text = shift; my $result = ''; for (extract_multiple $text, $extractor) { $_ = element(lc $1,$2) if /^($codes)<(.*)>$/; $result .= $_ unless (/^<!--/); } return $result; } # Handle a tag element with attribute if one exists, and then recurse +into it sub element { my ($id,$inner) = @_; return ($inner =~ s/\|([^<>]+?)$// ? "<$id $1>" : "<$id>") . inline($inner) . "</$id>"; } print inline 'Anyone who watches the Syfy channel knows that on Monday nights ' +. 'they aired three television series I<A<EurSUP<e>ka|href=' . '"">|class="title">, I<A<Wareh +ouse ' . '13|href="">>, and I<A<A +lphas' . '|href="">>. Some might not be + aware ' . 'that these three series have formed a crossover cosmology which I +call A<' . 'EWA|href=""><!-- This is a long stri +ng. -->';

Which prints the same output as in your example using Perl 5.8.8. The key is using extract_tagged which will match your codes exactly. For instance this is the results of the first extract_multiple :

'Anyone who watches the Syfy channel knows that on Monday nights they +aired three television series ' 'I<A<EurSUP<e>ka|href="">|class=" +title">' ', ' 'I<A<Warehouse 13|href="">> +' ', and ' 'I<A<Alphas|href="">>' '. Some might not be aware that these three series have formed a cross +over cosmology which I call ' 'A<EWA|href="">' '<!-- This is a long string. -->'

Everything is already broken up nicely and all that is left to do is recurse inside the tags found to handle any nested codes.

This does nothing more than your code however, as usual just TIMTOWTDI.