Is this a good way of returning an error messages from a subroutine in perl?
sub some_subroutine{
# do something
$something = 14;
if(1 == 2){
$_ = "This should not be happening!";
return undef;
}
return $something;
}
my $ret=some_subroutine();
print "ERROR: $_" unless(defined $ret);
The code runs OK (in a parallel world, where 1 == 2
), but using $_
to return the error message is a good way? I didn't found any documentation regarding the usage of $_
for this kind of purposes.
Thank you!
If an exception occurs within the try block, then it is handled by the appropriate exception handler (catch block), associated with the try block. If no exceptions are thrown, then try will return the result of block. A try block should have at least one (or more) catch block(s) or one finally block.
variables / $@ $EVAL_ERROR $@ The Perl error from the last eval operator, i.e. the last exception that was caught. For eval BLOCK , this is either a runtime error message or the string or reference die was called with. The eval STRING form also catches syntax errors and other compile time exceptions.
$_
is not a good mechanism as so many other things use and set it.
You could set some other global variable, like $Error, but the best way is to throw an exception. Then the user doesn't have to always check, and forget, it just happens. In Perl, exceptions are generated with "die". die will take a string or an object. There's a number of modules to make throwing exceptions easier including Exception::Class, Exception::Simple, Ouch and autodie.
You can catch the exception with eval {}, but there are a number of problems with that so you should use something like Try::Tiny.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With