Andrew Gaffney wrote:
>
> I have written the following code to generate HTML reports from Perl scripts. It
> works
> pretty well. I need to modify it to accept parameters for each column (e.g. column
> width,
> whether to total that column, etc.), but I can't figure out the best way to go about
> it.
>
> sub generate_report_html {
> my ($title, $columns, $data) = @_;
> print <<" EOF";
> <html>
> <body>
> <center><img src='/original_logo_60pc.jpg'><p>
> <h2>${title} Report</h2></center>
> <p>
> <table width=100%>
> <tr>
> EOF
> foreach (@$columns) {
> print "<td><b><u>$_</u></b></td>";
> }
> print "</tr>\n";
> foreach my $row (@$data) {
> print "<tr>";
> foreach (@$row) {
> print "<td>$_</td>";
> }
> print "</tr>\n";
> }
> print <<' EOF';
> </table>
> </body>
> </html>
> EOF
> }
>
> The code is called like:
>
> my $columns = ["Col1", "Col2", "Col3", "Col4"];
> my @data;
> while(...) {
> # Get data somehow
> push @data, ["$data1", "$data2", "$data3", "$data4"];
> }
> generate_report_html("report title", $columns, [EMAIL PROTECTED]);
>
> I want to be able to call it like:
>
> my $columns = [{width => 150, text => 'Col1', total => 0},
> {width => 100, text => 'Col2', total => 1},
> {width => 200, text => 'Col3', total => 1},
> {width => 100, text => 'Col4', total => 0}];
> my @data;
> while(...) {
> # Get data somehow
> push @data, ["$data1", "$data2", "$data3", "$data4"];
> }
> generate_report_html("report title", $columns, [EMAIL PROTECTED]);
Hi Andrew.
So your incoming $columns has changed from a reference to an
array of strings to an array or hash references.
The obvious solution is to get back to where you were in the first
place with something like:
sub generate_report_html {
my ($title, $columns, $data) = @_;
my @text = map $_->{text}, @$columns;
my @width = map $_->{width}, @$columns;
my @total = map $_->{total}, @$columns;
foreach (@text) {
print "<td><b><u>$_</u></b></td>";
}
:
}
and I think you can do the rest from there.
One other thing. I'm a great evangelist for defaults. In an ideal world
software should do what you want with no parameters at all, so I'd rather
see:
my $columns = [
{width => 150, text => 'Col1'},
{width => 100, text => 'Col2', total => 1},
{width => 200, text => 'Col3', total => 1},
{width => 100, text => 'Col4'}
];
so that the default is no total. $total[$i] will be undefined unless
explicitly set to a true value. You can still do
if ($total[$i]) {
:
}
without getting any warnings.
HTH,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>