in reply to alternating row colors

This is something that I like to use a closure for. The following will print a table with all of the URL and HTML codes, along with the symbol each stands for and the extended ASCII value. The $toggle variable controls the background color used for each row of the table.

use CGI; use HTML::Entities; use URI::Escape; my $q = CGI->new; my $data; my $toggle = initToggle( 1 ); for my $ASCII ( 0 .. 255 ) { # The following is a hexadecimal list of characters that must be e +ncoded # in query strings my $cgi_chars = '\x00-\x29\x2b\x2c\x2f\x3a-\x40\x5b-\x5e\x60\x7b- +\xff'; # The following is a hexadecimal list of characters that often hav +e their # HTML character code equivalent used instead of the characters th +emselves my $html_chars = '\x00-\x2f\x3a-\x40\x5b-\x5e\x60\x7b-\xff'; my $char = chr( $ASCII ); # The actua +l character my $symbol = encode_entities( $char, $html_chars ); # HTML code + for Web page my $escaped = uri_escape( $char, $cgi_chars ); # CGI repre +sentation my $html_code = encode_entities( $symbol ); # Re-encode + HTML code so that it # disp +lays properly if ( $escaped eq '%20' ) { $escaped .= ' or +' }; # a space m +ay be %20 or a + my @bgcolor = ( '#FFFFFF', '#CCCCCC' ); $data .= $q->Tr( { -align => 'right', -bgcolor => $bgcolor[ &$toggle ] }, $q->td( [ $ASCII < 33 ? '&nbsp;' : $symbol, $ASCI +I, $escaped, $html_code ] ) ); } print $q->header, $q->start_html, $q->table( $data ), $q->end_html; sub initToggle { my $limit = shift; my $count = 0; my $bit = 0; unless ( $limit > 0 ) { die "initToggle() requires a positive argu +ment\n" }; return sub { $bit ^= 1 if $count++ % $limit == 0; } }

In fact, if you wanted to, you could easily update the closure to return the color values themselves instead of the array index.

Yeah, I'm sure some of you recognize that table :)

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: (Ovid) Re: alternating row colors
by MeowChow (Vicar) on May 18, 2001 at 20:52 UTC
    The $bit variable in initToggle is superfluous:
    sub makeToggle { my $limit = shift; my $count = 0; die "makeToggle() requires a positive argument\n" unless $limit > 0; return sub { !($count++ % $limit); } }
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print