Reputation: 79
This works fine if a cookie already exists
use CGI::Cookie;
my %cookie = CGI::Cookie->fetch;
my $val = $cookie{'MY_COOKIE'}->value;
If there is no cookie, then the page failes with this error.
Can't call method "value" on an undefined value at /file.cgi line 23.
This test generates the same error... presumably because it's trying to do the same thing
if ( $cookie{'MY_COOKIE'}->value ) {
$val = $cookie{'MY_COOKIE'}->value;
}
How might I detect if there is no cookie or it has an empty value?
Thank you.
Upvotes: 2
Views: 316
Reputation: 10913
Try
use CGI::Cookie;
my %cookie = CGI::Cookie->fetch;
my $myCookie = $cookie{'MY_COOKIE'};
my $val = defined($myCookie) ? $myCookie->value : '';
OR
if( defined( my $myCookie = $cookie{'MY_COOKIE'} )) {
my $val = $myCookie->value;
# ...
}
Upvotes: 1
Reputation: 132896
If you have a value that should be an object but might not be, you can wrap the call in eval
to catch the error of calling a method on a non-object or undef value:
my $value = eval { $myCookie->value }; # maybe an object, maybe not
If $myCookie
isn't an object or doesn't have a value
method, $value
gets undef and your program continues. As I recall, CGI::Cookie
will not return an undef for a named cookie with no value; you'll get the (defined) empty string instead. So, if $value
is any defined value, including any false value, there was a cookie with that name.
In your case, you might have the wrong name for the cookie, so you are looking from the wrong cookie. You can use exists
to check for a key in a hash before proceeding:
if( exists $cookie{NAME} ) { ... }
But, that doesn't mean that the thing in $cookie{NAME}
is the sort of object you expect. You might want to check that it can respond to that method name before proceeding:
if( exists $cookie{NAME} and $cookie{NAME}->can('value') ) { ... }
You can't merely check if the $myCookie
is defined. You still don't know what's in it and your program blows up:
my $myCookie = 123;
if( defined $myCookie ) {
$myCookie->value; # still a fatal runtime error
}
Upvotes: 1