Reputation:
I'm trying to print an array elements in a table like this:
+------+-----+-------+------+
| One | Two | Three | Four | Header
+---------------------------+
| 1 | 2 | 3 | 4 | Row 1
+---------------------------+
| 5 | 6 | 7 | 8 | Row 2
+---------------------------+
I used this code:
my @array = ('1', '2', '3', '4', '5', '6', '7','8');
print $q->table({-border=>1},
$q->Tr($q->th(['One','Two','Three','Four'])),
$q->Tr($q->td(\@array))
);
But I end up with this:
+------+-----+-------+------+---------+
| One | Two | Three | Four | |
+---------------------------+---------+
| 1 | 2 | 3 | 4 | 5 6 7 8 |
+------+-----+-------+------+---------+
So what shall I do different to make it work?
Upvotes: 0
Views: 1750
Reputation: 69314
You've got a good answer already, but I just wanted to point out that using the HTML-generation functions from CGI.pm went out of fashion over fifteen years ago. You will find your application is far easier to maintain and improve if you switch to using a good templating system.
Upvotes: 0
Reputation: 6204
Perhaps the following will be helpful:
use strict;
use warnings;
use CGI ':standard';
my $q = CGI->new;
my @array = 1 .. 8;
my @td;
while ( my @elems = splice @array, 0, 4 ) {
push @td, $q->td( \@elems );
}
print $q->table(
{ -border => 1 },
$q->Tr( $q->th( [ 'One', 'Two', 'Three', 'Four' ] ) ),
$q->Tr( \@td )
);
Output (with manually-inserted newlines):
<table border="1">
<tr><th>One</th> <th>Two</th> <th>Three</th> <th>Four</th></tr>
<tr><td>1</td> <td>2</td> <td>3</td> <td>4</td></tr>
<tr><td>5</td> <td>6</td> <td>7</td> <td>8</td></tr>
</table>
Upvotes: 2