Question

I am using LWP::UserAgent like below

my $ua = LWP::UserAgent->new;

my $response = $ua->request ( ...);

if ( $response->is_success() )
{
...
}
print $response->is_success();

Problem I am facing is that is_success() is returning blank. I was expecting 1 (TRUE) or 0 (FALSE). What am I doing wrong here? Is print statement right?

Was it helpful?

Solution 3

From the discussion in comments:

$response->status_line 

actually returned 500 Can't Connect to database.

With $response->is_success(), I was unable to understand the response from db.

Used $response->status_line to find out exactly where the code was failing.

OTHER TIPS

Not returning anything is correct and usual way in Perl to return false result from function, don't expect literal 0 number when you only need logical false result. Your request is most likely returned with non 2xx or 3xx code.

From the Perl documentation:

The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context. All other values are true. Negation of a true value by ! or not returns a special false value. When evaluated as a string it is treated as "" , but as a number, it is treated as 0. Most Perl operators that return true or false behave this way.

In other words, your mistake is assuming that boolean false is always represented by 0. It would be more accurate to say that in Perl false is represented by "empty", with what that means depending on the context.

This is useful, because it allows for clean code in a variety of contexts:

#evaluates false when there are no more lines in the file to process
while (<FILE>) { ... }

#evaluates false when there are no array elements
if (!@array) { ... }

#evaluates false if this variable in your code (being used as a reference) 
#hasn't been pointed to anything yet.
unless ($my_reference) { ... }

And so on...

In your case, it's not clear why you want false to be equal to zero. The if() statement in your code should work as written. If you need the result to be explicitly numeric for some reason, you could do something like this:

my $numeric_true_false = ($response->is_success() ? 1 : 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top