2017-02-22 39 views
0

我試圖將.txt轉換爲.html格式。所以我嘗試了以下代碼進行轉換,並且還需要爲使​​用perl的表格格式中的每個列提供不同的標題名稱。如何使用Perl將.txt文件內容轉換爲.html格式?

輸入文件:input.txt

1:Explicit Placement blockages are created in the pad regions ?:Yes:INCORRECT:To Be Done 
2:Explicit Routing blockages are created in the pad regions ?:Yes:INCORRECT:To Be Done 
3:Is Complete bond pad meal is used for top level power hookup ?:Yes:INCORRECT:To Be Done 

代碼我嘗試:

#!/usr/bin/perl 
use strict; 
use warnings; 
open my $HTML, '>', 'output.html' or die $!; 
print $HTML <<'_END_HEADER_'; 
<html> 
<head><title></title></head> 
<body> 
_END_HEADER_ 
open my $IN, '<', 'input.txt' or die $!; 
while (my $line = <$IN>) { 
    $convert=split(/\:/,$line); 
    print $HTML $convert; 
} 
print $HTML '</body></html>'; 
close $HTML or die $!; 

預期輸出:

第1欄應根據序列號打印整個句子每線副。即從(顯式佈局堵塞在焊盤區域創建)

|s.no|column1  |column2|column3 |column4 | 
|1 |Explicit.... |yes |INCORRECT|To be done | 
|2 |Explicit.... |yes |INCORRECT|To be done | 
|1 |Is.......... |yes |INCORRECT|To be done | 
+0

是什麼您的預期輸出和您接收的輸出?因爲你提到了「每列的標題名稱」,但是你的代碼中沒有任何內容適用於列。如果它給你一個實際的錯誤或警告,那麼這個信息是什麼? – AntonH

+1

歡迎來到本網站!查看[tour](https://stackoverflow.com/tour)和[how-to-ask](https://stackoverflow.com/help/how-to-ask/)頁面,瞭解關於哪些人的更多信息正在找。在這種情況下,請[編輯您的問題](https://stackoverflow.com/posts/42400948/edit)以包含您期望的輸出以及您實際看到的輸出。 – cxw

+0

另外,'split'返回一個數組。你使用它的方式,標量,我相信會返回結果數組的大小,而不是分割的元素。 – AntonH

回答

4

以最小的改動代碼:

use strict; 
use warnings; 

open my $HTML, '>', 'output.html' or die $!; 
print $HTML <<'_END_HEADER_'; 
<html> 
<head><title></title></head> 
<body> 
<table> 
_END_HEADER_ 

open my $IN, '<', 'input.txt' or die $!; 
while (my $line = <$IN>) { 
    chomp $line; 
    print $HTML '<tr><td>' . join('</td><td>', split(/:/,$line)) . "</td></tr>\n"; 
    #or 
    #print $HTML '<tr><td>' . $line =~ s|:|</td><td>|gr . "</td></tr>\n"; 
} 
close $IN or die $!; 
print $HTML <<'_END_FOOTER_'; 
</table> 
</body> 
</html> 
_END_FOOTER_ 
close $HTML or die $!; 

會產生下面的HTML表:

<html> 
<head><title></title></head> 
<body> 
<table> 
<tr><td>1</td><td>Explicit Placement blockages are created in the pad regions ?</td><td>Yes</td><td>INCORRECT</td><td>To Be Done</td></tr> 
<tr><td>2</td><td>Explicit Routing blockages are created in the pad regions ?</td><td>Yes</td><td>INCORRECT</td><td>To Be Done</td></tr> 
<tr><td>3</td><td>Is Complete bond pad meal is used for top level power hookup ?</td><td>Yes</td><td>INCORRECT</td><td>To Be Done</td></tr> 
</table> 
</body> 
</html> 
+0

它工作正常@ jm666 –

相關問題