perl条件中的未定义值

Zee*_*han 2 cookies perl cgi

我是perl编程的初学者

我想在fetch中的值为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.

这是我的代码:

%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;
}
Run Code Online (Sandbox Code Playgroud)

fri*_*edo 9

null在Perl中没有,尽管有一个undef.null如果您在use strict打开的情况下运行,则会出现关于使用的错误,您应该始终这样做.

由于CGI::Cookie返回一个用于初始化哈希的列表,我们可以使用exists运算符来查看哈希中是否存在给定的键.

此外,由于条件的两个分支都会导致打印CGI标头,我们可以在条件之外移动它,我们可以使用标准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";
}
Run Code Online (Sandbox Code Playgroud)