Re: How to check if a DateTime is invalid (again - but this time without using eval)?

[email protected] ("Thomas (HFM) Wyant") Wed, 5 Jul 2017 10:59:15 -0400 (EDT)
Newsgroups perl.datetime
Message-ID <[email protected]>
> On July 3, 2017 at 7:09 AM Rick Measham <[email protected]> wrote:
> 
> 
>     I'm not sure what you mean by 'local DIE handlers'. Are you talking about defining a local $SIG{__DIE__} ?
> 
>     I've been out of perl for a couple of years, but surely you should just use eval{} ?
> 
> 
>     $dt = eval { $parser->parse( $input ); };
> 
> 
>     if( $@ ){
> 
>        echo "Unable to parse your date ($input)\n";
> 
>        exit;
> 
>     }
> 
>      
> 
>     echo "Your date is $dt\n";
> 
> 
>     - Rick
> 

One of the edge cases with eval {} is the possibility that $@ gets clobbered before you get your hands on it. I have never actually had this happen to me (or at least I have never recognized it) but because I have a tendency to blunder into situations where odd things happen I have developed the habit of having the eval {} always return a true value, and then testing the value of the eval {}. An exception will cause it to be false, even in the unlikely (IM(NS)HO) case of $@ getting clobbered. In this specific case,


my $dt = eval { $parser->parse( $input ) }
or die "Unable to parse your date ($input)\n";


Off-topic changes to the above include the use of the "... or die" pattern, which causes the output to go to STDERR and causes the script to terminate with the equivalent of "exit 1". I don't think echo() is standard Perl -- maybe a braino for print()?