[英]How do I read a text file by putting its data in a table using CGI in Perl?
The CGI to read the data from merch.txt works but how can I put this in a table? 从merch.txt读取数据的CGI有效,但是如何将其放在表中?
HTML File: HTML档案:
<form action="/cgi-bin/asst5/data.cgi" method="post">
<table border="2" cellspacing="5" cellpadding="5">
<tr>
<td align="center">SKU: </td>
<td><input type="text" name="code" size="15"></td>
</tr>
<tr>
<td align="center">Name: </td>
<td><input type="text" name="customer" size="15"></td>
</tr>
</table>
</form>
Data.CGI where data is accepted after it's been entered in the HTML Data.CGI,在HTML中输入数据后可以在其中接受数据
my $sku = param('code');
my $cust = param('customer');
print <<HERE;
<HTML>
<BODY>
SKU: $sku<br>
Name: $cust<br>
HERE
open (ORDERS, ">>merch.txt") or die "File error, $!";
print ORDERS "$sku|$cust\n";
close ORDERS;
Read.CGI This is the CGI file that reads the content from merch.txt Read.CGI这是从merch.txt中读取内容的CGI文件
open ( ORDERS, "merch.txt" ) or die "Error opening file, $!";
my @orders = <ORDERS>;
close ORDERS;
print <<here;
<HTML>
<BODY>
here
for (my $i = 0; $i < @orders; $i++ ) {
print "<td><pre>", CGI::escapeHTML($orders[$i])."<br>\n", "</pre></td>\n";
}
print <<MORE;
</BODY>
</HTML>
MORE
Using your raw embedded HTML approach, it's not hard. 使用原始的嵌入式HTML方法,并不难。 But it is incredibly ugly.
但这是丑陋的。
print <<END_OF_HTML;
<html>
<body>
<table>
<tr><th>Sku</th><th>Cust</th></tr>
END_OF_HTML
for (@orders) {
my ($sku, $cust) = split /\|/;
print '<tr><td>', CGI::escapeHTML($sku), '</td>',
'<td>', CGI::escapeHTML($cust), '</td></tr>';
}
print <<END_OF_HTML;
</table>
</body>
</html>
END_OF_HTML
But mixing raw HTML with your Perl code is a terrible idea . 但是,将原始HTML与Perl代码混合在一起是一个糟糕的主意 。 Please use a templating engine instead.
请改用模板引擎。 I recommend the Template Toolkit .
我建议使用模板工具包 。
Here's a simple CGI program using TT to do what you need. 这是一个使用TT完成您所需的简单CGI程序。
#!/usr/bin/perl
use strict;
use warnings;
use Template;
use CGI qw[header];
my $tt = Template->new;
# Best practice: three-arg open() and lexical filehandles
open my $ord_fh, '<', 'merch.txt' or die $!;
my @orders = <$ord_fh>;
close $ord_fh;
my @order_data = map {
my ($sku, $cust) = split /\|/;
{ sku => $sku, cust => $cust }
} @orders;
print header;
$tt->process('orders.tt', { orders => \@order_data })
or dir $tt->error;
And you'll need a template that looks something like this: 您将需要一个类似于以下内容的模板:
<html>
<head>
<title>Orders</title>
</head>
<body>
<h1>Orders</h1>
<table>
<tr><th>Sku</th><th>Cust</th></tr>
[% FOREACH order IN orders -%]
<tr><td>[% order.sku | html %]</td><td>[% order.cust | html %]</td></tr>
[% END -%]
</table>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.