Jon Bjornstad <[EMAIL PROTECTED]> wrote:

> I had a fragment of HTML that I needed to search
> for imbalanced tags and then remedy the
> situation by appending the right number of closing tags.
> 
> my ($no, $nc);
> for my $t (qw(ol ul b i u a)) {
>      $no = $frag =~ s/<$t\b/<$t/gi;
>      $nc = $frag =~ s#</$t\b#</$t#gi;
>      $frag .= "</$t>" x ($no-$nc) if $no > $nc;
> }
> 
> How about that last line? :)
> I don't often get to use the '.' operator or the 'x' operator
> and I thought this was pretty cool.

You don't often use the . operator?  No step-by-step 
construction of strings?  You *are* missing out on fun -- or 
maybe now.

Anyway, here's a very similar bit from a program I wrote some 
months back:

        # Close unclosed tags:
        for my $tag ( 'FONT', 'B' ) {
                my $uc_desc = uc($description);
                my($opens, $closes) = (0, 0);
                $opens++ while $uc_desc =~ m{<$tag}g;
                $closes++ while $uc_desc =~ m{</$tag}g;
                $description .= "</$tag>" x ( $opens - $closes )
                if $opens > $closes;
        }

I can't remember why I made an uppercase copy rather than 
using the /i modifier.  I'm sure I had some reason.  As to why 
I made the copy inside the loop, that seems to have been just 
an oversight.  I didn't use \b in the matches, but FONT and B 
were really the only HTML tags that occurred in the fragments 
I was dealing with.

-- 
Keith C. Ivey <[EMAIL PROTECTED]>
Washington, DC

Reply via email to