Basilides has asked for the wisdom of the Perl Monks concerning the following question:

Hi

If I query my database with

my @table = @{$sth->fetchall_arrayhref({})};
I'd then like to output each row of data as a row in an HTML table. Basically, something like:
print $query->table( $query->Tr( foreach @table { $query->td([$_->{name}, $_->{year}, $_->{rating}],) } ), );
But obviously I'm not allowed that foreach in the middle of my print statement.

What's a good way of doing this?

Cheers
Dennis

Replies are listed 'Best First'.
Re: Outputting data to tables with CGI.pm
by chromatic (Archbishop) on May 25, 2003 at 20:48 UTC
    print $query->table( $query->Tr( map { $query->td([$_->{name}, $_->{year}, $_->{rating}],) } @table ), );

    I wonder if you want the Tr() call inside of the map though.

Re: Outputting data to tables with CGI.pm
by The Mad Hatter (Priest) on May 25, 2003 at 20:21 UTC
    Personally, I find outputting HTML with CGI.pm atrocious. You could easily do this with a good templating system that allows loops, such as HTML::Template or Template Toolkit.
      +1, I tend to hate outputting HTML using commands, although it might be useful for simple pages. The tempalte choice is, IMHO, definitely better.
Re: Outputting data to tables with CGI.pm
by blokhead (Monsignor) on May 25, 2003 at 20:47 UTC
    I agree that CGI.pm's HTML formatting is ugly when mixed in with your code, but to answer your question, you need to use map to get a list of td's to put inside the Tr.
    use CGI qw/:standard/; # I prefer non-OO for these print table( Tr( [ map td( [ $_->{name}, $_->{year}, $_->{rating} ] ), @table ] ) );

    Update: you probably want to pass each group of 3 td's as an array ref [ ... ], instead of a flat array (which would put them all in one Tr).. I updated the code and now each Tr has 3 td's.

    blokhead

Re: Outputting data to tables with CGI.pm
by Basilides (Friar) on May 25, 2003 at 21:35 UTC
    Apologies for commenting on my own node--shows I didn't do enough RTFM before posting the question--but I've just found jeffa's very cool DBIx::XHTML_Table which does the job very nicely.