Amture101 Amture101 - 1 month ago 15
Perl Question

Printing array elements in CGI table in Perl

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?

Answer

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>