ealeon ealeon - 1 year ago 202
Perl Question

Perl: try::tiny to catch

use strict;
use warnings;
use Date::Parse;
use Try::Tiny;

my $etime = time;
my $stime = "";
my $dur = $etime - str2time($stime);
} catch {
print "error: $!\n";


Use of uninitialized value in subtraction (-) at perl_try.pl line 10.

Anyone know how to catch this?

This is not being caught in the catch block

Answer Source

Try::Tiny doesn't do anything here because the message is just a warning, not an exception or error.

perldoc Date::Parse:

str2time parses DATE and returns a unix time value, or undef upon failure.

So if you want to handle a parse error in str2time, you can simply check for undef:

my $parsed_time = str2time($stime);
if (!defined $parsed_time) {
    # ... handle this case
} else {
    my $dur = $etime - $parsed_time;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download