I am trying to do the following.
Take a block of text that a user inputs in a TEXTAREA FORM from a website and pass it to a perl/cgi script that adds the line number before each line. So for example:
diet coke
potato chips
gelato
would become
1 diet coke
2 potato chips
3 gelato
I know how to pass a single value or a bunch of values to a perl script, but when I try to do a foreach (@array) to add a line number it doesn't work. Wondering how to do this.
My html file is
<HTML>
<BODY>
<FORM ACTION="/cgi-bin/splitfoods.pl">
<P>What did you eat today? <BR><TEXTAREA NAME="value" ID="value" style="width:900px;height\
:700px;background-color:#FFF8DC;font-size:20px">
</TEXTAREA>
<P><INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
<开发者_开发技巧/HTML>
and the cgi file is (from matthewh)
#!/usr/bin/perl
use CGI;
use CGI qw(:standard);
$query = new CGI;
@foods = split('\n',$query->param("value"));
# -- HTML STUFF --
print header;
print start_html;
for($i=1; $i<=@foods; $i++) {
print "$i @foods[$i-1]";
print "<br>";
}
print end_html;
request looks like
cgi-bin/splitfoods.pl?value=diet+coke%0D%0Apotato+chips%0D%0Agelato
Thanks
@foods = split('\n',$query->param('food'));
for($i=1; $i<=@foods; $i++) {
print "$i @foods[$i-1]\n";
}
This is a bit cleaner and less likely to breakdown on edge cases. Plus the numbering is HTML instead which is more natural for web. You really should read the entire document for CGI and always start code with warnings and strict on.
use strict;
use warnings;
no warnings "uninitialized";
use CGI ":standard";
# Scalar/array context matters with param()!
my $food = param("value");
my @foods = split /\n/, $food;
print
header(),
start_html(),
ol(li( \@foods )),
end_html();
精彩评论