使用foreach创建Perl CGI表



我刚刚玩过Perl CGI和SQLite。我以为这样的东西可以胜任这份工作。

my $res = $dbh->selectall_arrayref("SELECT name, surename, phone FROM status;"),
print $cgi->table(
$cgi->Tr(
    { -align => "CENTER", -valign => "TOP" },
    $cgi->th( [ 'Name', 'Surename', 'Phone' ] )
),
foreach my $row (@$res){
    ( $name, $surename, $phone ) = @$row,
    print $cgi->Tr( $cgi->td($name), $cgi->td($surename), $cgi->td($phone) ),
  }
);

是否需要手动创建HTML文档的表?

您应该熟悉CGI模块的POD。在这里你可以找到一个创建表的例子:

print table({-border=>undef},
           caption('When Should You Eat Your Vegetables?'),
           Tr({-align=>'CENTER',-valign=>'TOP'},
           [
              th(['Vegetable', 'Breakfast','Lunch','Dinner']),
              td(['Tomatoes' , 'no', 'yes', 'yes']),
              td(['Broccoli' , 'no', 'no',  'yes']),
              td(['Onions'   , 'yes','yes', 'yes'])
           ]
           )
        );

正如您从示例中看到的,您确实需要指定表格中的成分。CGI模块的HTML标记帮助程序并不是很神奇;它们只是Perl函数(或方法,具体取决于您如何使用模块),它们与它们所代表的HTML非常相似。如果您必须在HTML中键入<table><tr><th>...,那么您的标记助手将需要是tableTrth等。在循环中使用标记或标记助手的组合是可以的,只要获得输出的HTML对浏览器来说是可理解的。

使用CGI模块的脚本可以从命令行运行,这是一个很好的调试工具,因为它们会转储原始HTML并在屏幕上进行查看。

答案是否定的。这两行代码:

my $cats = $db->selectall_arrayref("select * from pubs..authors");
print map { $q->Tr(undef, $q->td($_)) ."n"} @$cats;

会给你(好吧,我…)

<tr><td>172-32-1176</td> <td>White</td> <td>Johnson</td> <td>408 496-7223</td>     <td>10932 Bigge Rd.</td> <td>Menlo Park</td> <td>CA</td> <td>94025</td> <td>1</td></tr>
<tr><td>213-46-8915</td> <td>Green</td> <td>Marjorie</td> <td>415 986-7020</td> <td>309 63rd St. #411</td> <td>Oakland</td> <td>CA</td> <td>94618</td> <td>1</td></tr>
<tr><td>238-95-7766</td> <td>Carson</td> <td>Cheryl</td> <td>415 548-7723</td> <td>589 Darwin Ln.</td> <td>Berkeley</td> <td>CA</td> <td>94705</td> <td>1</td></tr>
.... and however many more authors from pubs

为了完整起见,使用hashref,您可以像一样拉出标题

my $cats = $db->selectall_hashref("select * from pubs..authors", [ au_id]);
my @rows = values %$cats; # array of hashes now
print $q->Tr(undef, $q->th([keys( %$rows[0] )])),"n"; #borrow keys from first guy 
print map { $q->Tr(undef, $q->td( [ values(%$_) ] ) ),"n"; }  @rows;

最新更新