2014-04-19 57 views
-1

我必須從文件讀取值,將它們存儲在數組中,然後將值輸出到HTML文件中的HTML表格中。做這個的最好方式是什麼?使用write()和format來寫入文件,使用CGI和print來寫入文件,或者只是打印tr和td的?如何從Perl中將HTML表格輸出到文件中?

我有三列四行(12個值)。

回答

0

只需使用formatwrite()和一個循環來控制輸入。像這樣:

while($i<10){ 
     $name = $values[$i]; 
     $description = $values[$i+1]; 
     $price = $values[$i+2]; 
     write; 
     $i = $i+3; 
    } 


    format BODY = 
    <tr><td>@*</td><td>@*</td><td>[email protected]####.##</td></tr> 
      $name,   $description,       $price 
    . 
2

我喜歡格式,但我不會爲此使用它。格式所擅長的事物在這裏不會發揮作用。

簡單print聲明將做。 splice是一個被低估的內置,可以從陣列中的一個去刪除幾個要素:

use HTML::Entities qw(encode_entities); 

my @values = (
    'a' .. 'd', 
    'cats & dogs', '</div>', '"quotes"', 
    '<script src="foo.js"/>', 
    'e' .. 'f' 
    ); 

my $elements_per_row = 3; 

print "<table>\n"; 
while(my @row = splice @values, 0, $elements_per_row,()) { 
    print 
     '<tr>', 
     map( 
      { '<td>' . encode_entities($row[$_]) . '</td>' } 
      0 .. $elements_per_row - 1 
      ), 
     '</tr>', "\n" 
    } 
print "</table>\n"; 

但是,你應該考慮使用某種類型的模板系統從程序分開你的HTML。有幾種可用於Perl。

相關問題