in reply to HTML Table Using Perl

You're appending to a global variable in html_row. Quit that! :)

You want a new $rowP and $tableP on each subroutine call. Using the -w flag and strict is not just a good idea, it's almost a requirement for CGI scripts in Perl. Here's the fixed code:

#!/usr/bin/perl -w use strict; print "Content-type: text/html\r\n\r\n"; # generate an HTML table of the powers of 2,3 and 4 my @rows = html_row("white"," n ", "nth power of 2", "nth power of 3", "nth power of 4"); for (0 .. 10) { if ($_ % 2) { push @rows, html_row("#cccccc",$_,2**$_,3**$_,4**$_); } else { push @rows, html_row("#ccccff",$_,2**$_,3**$_,4**$_); } } my $table = html_table(1,"",@rows); my $table2 = html_table(0,"black",html_row("",$table)); print "Here are the powers of 2, 3 and 4<BR><BR>\n"; print "$table2"; # This subroutine will print out a table row sub html_row { my $color = shift; my $rowP = "<TR BGCOLOR=$color><TD>"; $rowP .= join("</TD><TD>", @_) . "</TD></TR>\n"; return $rowP; } # This subroutine will print out an HTML Table sub html_table { my $border = shift; my $color = shift; my $tableP ="<TABLE BORDER=$border BGCOLOR=$color>\n"; $tableP .= join('', @_) . "</TABLE>\n"; return $tableP; }
Note that this code is a lot shorter, and makes use of happy magic variables like @_.

The biggest change is declaring all of the variables with my. This is what fixed your error. Oh, and the closing table tag bug is fixed in my version too.

Replies are listed 'Best First'.
RE: Re: HTML Table Using Perl
by Fastolfe (Vicar) on Oct 26, 2000 at 05:56 UTC
    This is exactly why we have things like the strict pragma. PLEASE, if you have any unusual behavior in your scripts, be certain that you are useing strict and that your code generates no warnings with -w. This would have caught your problem (or at least forced you to think about the scoping of this variable, which I would hope would have brought attention to the issue)!
RE: Re: HTML Table Using Perl
by Maclir (Curate) on Oct 26, 2000 at 05:16 UTC
    You may also want to add a "sanity check" to the allocation of values to the BORDER and BGCOLOR lines too. Maybe even surround the values by double quotes, just in case something wierd gets passed to them which may break the HTML.