如何避免多次打印某些表格内容?

时间:2012-05-29 14:48:04

标签: html perl

我尝试通过在Perl脚本中硬编码HTML标记来创建HTML表。我从文本文件中获取数据,然后按组件拆分它们并将它们打印到HTML表中。文本文件示例(作者,书名,书籍内容):

Ronnie Smith, javabook, javaclasses
Ronnie Smith, javabook, javamethods
Ronnie Smith,  c-book, pointers
Carrlos Bater, htmlbook, htmltables

如何打印作者姓名一次而不是打印三次,而且书名相同?只有一位作者Ronnie Smith写了三本书,所以它应归入一个类别。例如, javaclassesjavamethods来自同一本书javabook,因此我们应该只打印一次javabook

我的剧本:

use strict;
use warnings;

my $Author;
my $bookName;
my $bookContent;
my $bookContentList = "List.txt";

open MYFILE, $bookContentList or die "could not open $bookContentList \n";

my @body = "";
push(@body, "<html> \n");
push(@body, "<head> \n");
push(@body, "<TABLE BORDER=\"0\"\n");
push(@body, " <TD>");
push(@body, "<div align=\"left\"><Table border=1 bordercolor= \"black\"> \n");
push(@body, "<tr bgcolor=\"white\"><TH><b>Author</b></TH><TH>Book Name     </TH><TH>bookContent</TH></TR>");
push(@body, "<br>\n");

while (<MYFILE>) {
    ($Author, $bookName, $bookContent) = split(",");
    push(
        @body, "<TR><td>$Author</TD>
         <td>$bookName</TD>
         <td>$bookContent</TD>"
    );
}
push(@body, "</div></Table>");

my $Joining = join('', @body);
push(@body, "</body></font>");
push(@body, "</html>");
my $htmlfile = "compliance.html";
open(HTML, ">$htmlfile") || warn("Can not create file");
print HTML "$Joining";
close HTML;
close MYFILE;

1 个答案:

答案 0 :(得分:0)

这是哈希表的典型案例:您希望通过唯一标识符识别作者和书籍:

my ( %author_books, @author_order );
while (<MYFILE>) {
    ($author, $bookName, $bookContent) = split(",");
    my $auth = $author_books{ $author };
    unless ( $auth ) { 
        push @author_order, $author;
        $author_books{ $author } = $auth = {};
    }
    my $books= $auth->{books}{ $bookName };
    unless ( $books) { 
        push @{ $auth->{order} }, $bookName;
        $auth->{books}{ $bookName } = $books= [];
    }
    push @$books, $bookContent;
}

foreach my $author ( @author_order ) { 
    my $auth  = $author_books{ $author };
    my $books = $auth->{order}; 
    push @body, qq{<tr><td rowspan="${\scalar @$books}">$author</td>\n};
    my $line = 0;
    foreach my $book ( @$books ) { 
        push @body, '<tr><td></td>' if ++$line;
        push @body
           , ( "<td>$book</td><td>"
             . join( "<br/>\n", @{ $auth->{books}{ $book } } )
             . "</td><tr>\n"
             );
    }
}

我不推荐push @body方法。但如果你要这样做,我会推荐File::Slurp

File::Slurp::write_file( $htmlfile, @body );

通过这种方式,你也可以跳过加入$Joining过早的错误,并且没有像你那样写出页脚。