Perl - 在for循环中验证参数的问题

问题描述 投票:-1回答:1

该脚本捕获5x2输入字段。

for ($i=0;$i<6;$i++) {

   $zeit_[$i] = $q->param("zeit_[$i]");
   $tatigkeit_[$i] = $q->param("tatigkeit_[$i]");

   ##validation

   if (!$zeit_[1]) 
      {&error('Bitte geben Sie mindestens eine Aktivität an!');}
   if ($zeit_[$i] =~ /\D/) 
      {&error('Die Zeitangabe zur Aktivität "'. $tatigkeit_[$i] . '"enthält ein unzulässiges Zeichen! Bitte geben Sie nur ganze Zahlen an!');}
   if ($tatigkeit_[$i] =~ /[^A-Za-z0-9öäüÖÄÜß-\s]/) 
      {&error('Die Tätigkeit "' . $tatigkeit_[$i] . '" enthält ein unzulässiges Zeichen!');}

   #prepare the output
   if ($zeit_[$i]) {$ausgabe.= $zeit_[$i] . " mit " . $tatigkeit_[$i] . " ID: $i<br>";}

}
print "Content-type: text/html\n\n";
print $ausgabe; exit();

我的问题是这个验证(必须填写第一个输入):

if (!$zeit_[1]) 
  {&error('Bitte geben Sie mindestens eine Aktivität an!');}

验证子程序error在所有情况下都会发生。空输入,也填充一个或所有五个输入。

当我对验证进行否定时

if ($zeit_[1]) 
  {&error('Bitte geben Sie mindestens eine Aktivität an!');}

qazxsw poi也出现了。我认为问题是var qazxsw poi

当我用error禁用验证时 - 脚本运行正常。输出显示所有10个元素。

可能有人给我一个提示?

This update fixed the problem

$zeit_[1]改为#。正确代码:

for ($i=0;$i<6;$i++)
perl for-loop
1个回答
2
投票

我猜这是一个简单的拼写错误。但是你没有向我们展示你期望的输入数据,所以除了猜测之外别无他法。

(我也猜测这是一个使用CGI.pm编写的CGI程序 - 如果你能在你的问题中指出这一点会更好。)

在验证中,您有:

for ($i=1;$i<6;$i++)

但在其他验证线上,您有:

for ($i=1;$i<6;$i++) {

   $zeit_[$i] = $q->param("zeit_[$i]");
   $tatigkeit_[$i] = $q->param("tatigkeit_[$i]");

   ##validation

   if (!$zeit_[1]) 
     {&error('Bitte geben Sie mindestens eine Aktivität an!');}
   if ($zeit_[$i] =~ /\D/) 
     {&error('Die Zeitangabe zur Aktivität "'. $tatigkeit_[$i] . '"enthält ein unzulässiges Zeichen! Bitte geben Sie nur ganze Zahlen an!');}
   if ($tatigkeit_[$i] =~ /[^A-Za-z0-9öäüÖÄÜß-\s]/) 
     {&error('Die Tätigkeit "' . $tatigkeit_[$i] . '" enthält ein unzulässiges Zeichen!');}

   #prepare the output
   if ($zeit_[$i]) {$ausgabe.= $zeit_[$i] . " mit " . $tatigkeit_[$i] . " ID: $i<br>";}

}
print "Content-type: text/html\n\n";
print $ausgabe; exit();

在一个案例中检查if (!$zeit_[1]) 和在其他案例中检查if ($zeit_[$i] =~ /\D/) 似乎没有意义。在任何情况下,$zeit_[1]都不会在循环的第一次迭代中设置(其中$zeit_[$i]为0,因此$zeit_[1]将不会被赋予值)。

其他一些Perl技巧:

  • 如果你把它写成$i,那么$zeit_[1]就容易理解了。
  • 在子程序调用中不需要使用for ($i=0;$i<6;$i++)for my $i (0 .. 5)的工作方式与&一样(并且不会让非Perl程序员感到困惑)。
  • 如果您正在使用CGI.pm(并且调用error(...)暗示您是),那么您可以使用&error(...)来创建CGI标头。

更新:考虑到我们学到的一切,我会写得更像这样:

$q->param(...)
© www.soinside.com 2019 - 2024. All rights reserved.