develooper Front page | perl.fwp | Postings from July 2003

Re: Is this fun?

Thread Previous | Thread Next
Keith C. Ivey
July 14, 2003 17:13
Re: Is this fun?
Message ID:
Jon Bjornstad <> 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 <>
Washington, DC

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About