2016-06-11 12 views
1

我有一個Perl CGI測驗,但我完全停留在它上面。我的HTML代碼如下:Perl CGI - 爲特定性選擇無線電值

<p class="question"><br>1. The answer is Number 1 </p> 
 
<ul class="answers"> 
 
    <input type="radio" name="q1" value="a" id="q1a"><label for="q1a">1912</label><br/> 
 
    <input type="radio" name="q1" value="b" id="q1b"><label for="q1b">1922</label><br/> 
 
    <input type="radio" name="q1" value="c" id="q1c"><label for="q1c">1925</label><br/> 
 
    <input type="radio" name="q1" value="d" id="q1d"><label   for="q1d">Summer of '69</label><br/> 
 
</ul>

CGI程序是從它的參數值的單選按鈕,選擇名字。我的Perl代碼如下:

if (param("q1") eq undef) { 
    $an1 = 0; 
    $winner = 0; 
print <<"BIG"; 
     <h1>You didn't enter the right answer</h1> 
BIG 
} 
else { 
print <<"BIG"; 
     <h1>You entered the right answer</h1> 
BIG 
} 

在這一點上,它會說我輸入正確的答案,如果我檢查任何收音機框。

有一些方法我可以指定哪些看重它從收音機採摘,像abcd的參數,還是我做錯了乾脆?

回答

2

請參閱CGI documentation瞭解有關如何處理無線電組的詳情。 給你舉個例子:

my $cgi = CGI->new; 
my $value = $cgi->param('q1'); 

if ($value eq 'a') { #correct answer 

} 
else { # incorrect answer 
} 

此外,eq是一個字符串比較操作,不要用它來測試undef。 Perl對此有一個defined函數。

1

必須始終use strictuse warnings 'all' Perl程序的頂部。在那些地方,您會看到消息Use of uninitialized value in string eq

您無法使用字符串比較器eq將值與undef進行比較。在你的情況下,param("q1")將是a,b,cd,或者如果沒有選擇任何單選按鈕,或許undef。 (你通常會默認選擇其中一個單選按鈕來避免這種情況,使用checked="checked"。)

這是一個基本的CGI程序,可以正常工作。

use strict; 
use warnings 'all'; 

use CGI::Minimal; 
use File::Spec::Functions 'abs2rel'; 

my $self = abs2rel($0, $ENV{DOCUMENT_ROOT}); 

my $cgi = CGI::Minimal->new; 

my $q1 = $cgi->param('q1') // 'none'; 

my $message = 
     ($q1 eq 'a') ? "<h3>You entered the right answer</h3>" : 
     ($q1 ne 'none') ? "<h3>You didn't enter the right answer</h3>" : 
     ''; 

print <<END; 
Content-Type: text/html 

<html> 
    <head> 
     <title>Test Form</title> 
    </head> 
    <body> 

     <form action="$self"> 

      <p class="question"><br/> 
      1. The answer is Number 1 
      </p> 

      <ul class="answers"> 

       <input type="radio" name="q1" value="none" id="q1a" checked="checked" /> 
       <label for="q1a"><i>Please choose an answer</i></label> 
       <br/> 

       <input type="radio" name="q1" value="a" id="q1a" /> 
       <label for="q1a">1912</label> 
       <br/> 

       <input type="radio" name="q1" value="b" id="q1b" /> 
       <label for="q1b">1922</label> 
       <br/> 

       <input type="radio" name="q1" value="c" id="q1c" /> 
       <label for="q1c">1925</label> 
       <br/> 

       <input type="radio" name="q1" value="d" id="q1d" /> 
       <label for="q1d">Summer of '69</label> 
       <br/> 
      </ul> 

      <input type="submit"> 

     </form> 

     $message 

    </body> 
</html> 

END 
1

你應該試試這個

$radio_value = $cgi->param('q1') 

也結束的HTML標籤BIG後它似乎沒有結束,因爲它的鋼紅了!你編寫與打印線!

+0

堆棧溢出語法突出顯示器對於Perl來說不是很聰明。但是你是對的,HEREDOC定界符後應該有空行。 – simbabque