Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning error messages from perl subroutines

Tags:

perl

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!

like image 921
Gogu Talent Avatar asked Apr 14 '11 23:04

Gogu Talent


People also ask

How do I catch an exception in Perl?

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.

What is $@ Perl?

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.


1 Answers

$_ 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.

like image 181
Schwern Avatar answered Sep 20 '22 13:09

Schwern