After I don't know how many years of using perl, l I finally decided to take 5 minutes and figure out how exception handling works, and I'm ashamed that I didn't really dig into this a long time ago. It's wonderful. Duh.
The magic eval construct does this, and it traps any perl errors that happen within, retaining control over execution. eval returns the result of its last expression, and sets the $@ variable to any error string upon failure.
In my example, I had a set of routines that had a lot of parsing to do, and if any errors happened, we could just bail and return to the caller by calling die with an error string. The eval intercepted the die and set the $@ variable to the error string.
In the main code:
This has dramatically simplified my code - how dumb that I've not been using this for years - guess I learn something new every day.while ( my $input = <STDIN> ) { my $result = eval { parser($input) }; if ( $@ ) { print "Error: $@ on line $.\n"; } else { # process $result as usual } } .... sub parser { my $line = shift; ... if ( failure condition ) { die "Something broken in parser()\n"; } ... return "result"; }
See the perl docs for full info on eval.
Posted by Steve at September 17, 2002 07:13 AM
| TrackBack
Eval is AMAZING. The XML-RPC module that comes with SOAP::Lite actually crashes if the server it communicates with comes back with a 500 error. Crashes! Eval saves the day once again.
Posted by: MTS on October 16, 2002 04:48 PM