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.


In reply to Re: HTML Table Using Perl by chromatic
in thread HTML Table Using Perl by Kiko

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.