我是 perl 编程的初学者
我想在获取的值为 null 时执行一部分代码,这意味着不存在 cookie,如果存在 cookie,则执行另一部分代码。
但是我遇到了错误:
软件错误:
Can't call method "value" on an undefined value at /net/rtulmx0100/fs7/www/LabelMeDev_Student/annotationTools/perl/session_test.cgi line 93, <FP> line 3.
Here is my code :
%cookies = CGI::Cookie->fetch;
$id = $cookies{'name'}->value;
if($id == null)
{
print "Content-Type: text/plain\n\n" ;
print "hahahah";
}
else{
print "Content-Type: text/plain\n\n" ;
print $id;
}
最佳答案
Perl 中没有null
,尽管有undef
。如果您在打开use strict
的情况下运行,您会遇到有关使用null
的错误,您应该始终这样做。
由于 CGI::Cookie
返回一个用于初始化散列的列表,我们可以使用 exists
运算符以查看哈希中是否存在给定键。
此外,由于条件的两个分支都会打印 CGI header ,我们可以将其移到条件之外,我们可以使用标准 CGI模块来完成它。
use strict;
use warnings;
use CGI;
use CGI::Cookie;
my $q = CGI->new;
print $q->header( 'text/plain' );
my %cookies = CGI::Cookie->fetch;
if ( exists $cookies{name} ) {
print $cookies{name}->value;
} else {
print "hahahah";
}
关于perl - perl 条件下的未定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18517306/