2016-11-01 18 views
0

文本文件中的項目用管道符號「|」分隔。下面的CGI文件將在指定標籤下的表格中顯示這些項目。請看這Table Output,這就是我所擁有的。我該如何解決這些問題,因爲這些項目是在他們指定的專欄中,而不僅僅是一個?有沒有MySQL或SQL來保存數據,只是一個文本文件PERL CGI:如何修正拆分功能,讀取/顯示錶格上的數據?

#!/usr/bin/perl -w 
use CGI qw(:standard); 
use CGI::Carp qw(fatalsToBrowser); 
use strict; 
use warnings; 
print "Content-type: text/html\n\n"; 

print "<TABLE BORDER>\n"; 
print "<TR><TH>SKU Code<TH>Name<TH>Description<TH>Price"; 

open (ORDERS, "inventory.txt") or die "Error opening file, $!"; 
while(<ORDERS>) { 
    print "<TR>\n"; 
    print "<TD>"; 
my @fields=split(/\<\*\>/); 
    print join(`<TD>`,@fields); 
    print "</TR>"; 
} 
close ORDERS; 
print "</TABLE>"; 

下面是一個用來存儲項目的文本文件中的CGI文件

#!/usr/bin/perl -w 
use strict; 
use warnings; 
use CGI qw(:standard); 
use CGI::Carp qw(fatalsToBrowser); 
print "Content-type: text/html\n\n"; 
my $sku = param('sku_code'); 
my $cust = param('customer'); 
my $description = param('description'); 
my $selling = param('price'); 
my $price = sprintf("\$%.2f"); 

print <<HERE; 
<HTML> 
<BODY> 
<H3>Here is your order...please check</H3> 
SKU: $sku<br> 
Name: $cust<br> 
Description: $description<br> 
Selling Price: $price<br> 
HERE 
open (ORDERS, ">>inventory.txt") or die "File error, $!"; 

print ORDERS "$sku|$cust|$description|$price\n"; 
close ORDERS; 

回答

3

這樣的事情會工作。

# Best practice: three-arg open() and lexical filehandle 
open my $order_fh, '<', 'inventory.txt' or die "Error opening file, $!"; 

while(<$order_fh>) { 
    print "<TR>\n"; 
    print '<TD>' . join('</TD><TD>', split /\|/) . "</TD>\n"; 
    print "</TR>\n"; 
} 

close $order_fh; 

此代碼看起來像rather familiar。請考慮我在那裏給出的關於使用模板系統的建議。

在你的代碼的一些其他意見:

  • use warnings取代-w。你不需要兩個。
  • 使用header()(來自CGI.pm)打印標題。
  • my $price = sprintf("\$%.2f") - 這看起來不對!
  • 你真的需要添加一些文件鎖定。
  • 您的HTML看起來像是從1995年開始的。我們傾向於近期關閉元素。
+0

謝謝。這非常有幫助 –

0

拆分訂單的每一行通過管道字符,你應該說:

my @fields=split(/\|/, $_); 
+0

該表似乎沒有任何更改。 –

+0

對不起,複製粘貼格式化很好吃了反斜槓 – sotona