2012-05-29 77 views
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; 

回答

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並沒有寫出來的頁腳,像你這樣的錯誤。

+0

嘿謝謝您的回覆,但由於某種原因,我在嘗試編譯時遇到錯誤。它說:「標量找到了操作符在file.pl附近的位置」 $ author \ n「; MISSING OPERATOR BEFORE $?和另一個是String found where opeartor預計 $ author \ n「;缺少作業者在$作者之前。 – Maxyie

+0

啊,是的。我不能使用雙引號將整個字符串和屬性值分隔符分隔開來。 – Axeman