【问题标题】:I have a perl script that is passing a parameter in from an html file and then prints that parameter to the file我有一个 perl 脚本,它从 html 文件中传递一个参数,然后将该参数打印到文件中
【发布时间】:2014-06-17 06:40:11
【问题描述】:

所以我编写了一个 perl 脚本来从 HTML 文件中传递一个参数,然后获取该参数的值并将其写入文件,然后读取文件并编译数据。这是html文件的主体:

    <!DOCTYPE html>
<!DOCTYPE html>
<html lang = "en">
<head>
<title> poll.html </title>
<meta charset = "utf-8" />
<style type = "text/css">     
</style>
</head>
<!-- the quiz -->
<body>
<form action = "../cgi-bin/poll.pl" method = "post">
</h1> this is a poll<br><br>What is your favorite color?</h1>
<input type="radio" name="color" value="red">Red<br>
<input type="radio" name="color" value="green">Green<br>
<input type="radio" name="color" value="blue">Blue<br>
        <input type = "submit"  value = "Submit Quiz" />

    </form>
</body>
</html>

然后我的 perl 脚本可以正常工作,但是一旦打开文件,我就会丢失 $color 的值或 poll.pl 第 19 行的字符串。)这里是 perl 脚本: #!/usr/bin/perl -w

# processOrder.pl
use CGI ":standard";
use strict;
use warnings;
print header;
print start_html("Pizza Places Order Form");
#Set local variables to the parameter values 
our($color)=param("color");
my $filename = 'data.txt';
open(my $fh, '+>>', $filename) or die "Could not open file '$filename' $!";
print $fh "'$color'\n";
my $red = 0;
my $blue = 0;
my $green = 0;
while( my $line = <$fh>)  {   
    if (index($line, "red\n") != -1) {
    $blue = $blue + 1;} 
if (index($line, "blue\n") != -1) {
    $blue = $blue + 1;}
if (index($line, "gren\n") != -1) {
    $green = $green + 1;}
}
my $total = $red + $green +$blue;
if ($total == 0){
$total = 1}
print  h4("percent blue = ", $blue/$total, "\n");
print  h4("percent green = ", $green/$total,  "\n");
print  h4("percent red = ", $red/$total, "\n");
close $fh; 

最后警告我是 perl 的新手,但我确实认为这个逻辑是合理的,任何帮助都会很棒。谢谢

【问题讨论】:

  • 你“失去了$color的价值”是什么意思?
  • 当使用 /usr/bin/perl 编译脚本时会遇到一个错误,提示我无法将 $color 值打印到此文件,因为它尚未初始化。我初始化了它,但编译器认为它还没有初始化,我似乎无法找到一种方法让它认为它已经初始化。

标签: perl


【解决方案1】:

您的脚本存在许多问题。以下是三个主要的:

  1. 您将文本附加到文件的末尾,然后尝试读取文件的内容。问题是您的读取光标位于文件末尾,因此您什么也没读。在尝试读取文件之前,您需要将读取光标重置到文件的开头。使用seek $fh, 0, 0;
  2. 您将'blue' 附加到文件中,但您将其与blue 进行比较(您缺少单引号)。你永远不会得到任何匹配。
  3. 您测试该行是否与red\n 匹配,如果匹配...则增加$blue

【讨论】:

    【解决方案2】:

    我知道这是一个较旧的线程,但我也注意到一件事是您没有使用 chomp。当您从标准输入(或从表单或其他任何内容)读取并想要将其与字符串进行比较时,最好先 chomp($var) 摆脱换行符。如果没有换行符,则该函数不执行任何操作(与 Chop() 不同,它将删除最后一个字符,无论它是什么。)

    所以这个:

    if (index($line, "red\n") != -1) {
    

    会变成这样:

    if (index(chomp($line), "red") != -1) {
    

    这没什么大不了的,但如果您不确定是否有换行符,这是一个很好的做法。如果您正在读取的字符串位于文件末尾并且没有换行符,则尤其如此,这至少在 *nix 环境中是相对常见的。

    【讨论】:

      猜你喜欢
      • 2022-10-02
      • 2017-12-05
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 2021-09-04
      • 2018-06-14
      • 2021-04-24
      相关资源
      最近更新 更多