0

我尝试通过在 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;
4

1 回答 1

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像您一样跳过加入太早和未能写出页脚的错误。

于 2012-05-29T16:21:33.843 回答