What is the best way to raise errors in the Perl method for the caller

Given a method that might fail with warnings and / or errors, I want the error method to be displayed by the caller. Fir enter this script:

foo(0);         # line 1

sub foo {
    1 / shift;  # line 4
}

Throws an error Illegal division by zero at foo.pl line 4, but I want to Illegal division by zero at foo.pl line 1. There should be several ways if I put this method in a module, or if I wrap my method body in eval, but I did not find a simple way:

sub foo {
    attributeErrorsToCaller; # do some magic
    1 / shift;
}

Is there such a way?


EDIT: mirod answer is not close to what I was looking for:

Foo::foo(0);         # line 1

package Foo;
use diagnostics -traceonly;
BEGIN { disable diagnostics; }

sub foo {
    enable diagnostics;
    1 / shift;       # line 9
}

No enable diagnosticserror message Illegal division by zero at foo.pl line 9.. With enable diagnosticsit it is still too verbose, but it can also be useful:

Uncaught exception from user code:
    Illegal division by zero at foo.pl line 10.
 at foo.pl line 10
     Foo::foo(0) called at foo.pl line 2

, "hack" , , , , .

+5
3

use diagnostics; ? , .

, :

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;


foo(0);

sub foo
  { 
    return 1/$_[0];
  }

:

`Illegal division by zero at test_die line 12 (#1)
    (F) You tried to divide a number by 0.  Either something was wrong in
    your logic, or you need to put a conditional in to guard against
    meaningless input.

Uncaught exception from user code:
        Illegal division by zero at test_die line 12.
 at test_die line 12
        main::foo(0) called at test_die line 8
+6

Carp , "do_some_magic", . :

#!/usr/bin/perl -w 
use strict;

# I fork to be as close to natural die() as possible. 
fork() or Foo::foo();
fork() or Foo::bar();
fork() or Foo::baz();
sleep 1;

package Foo;
use Carp; 

sub foo { die "Some error (foo)"; }; 
sub bar { croak "Some error (bar)"; }; 
sub baz { bar(); };

, croak() die(), ( - . baz).

1/0 - eval ( Try:: Tiny), * " " .

Carp , , , confess cluck print Carp::longmess (. ).

*,

+10

, . Debug:: Trace, .

perl caller, . , , .

http://perldoc.perl.org/functions/caller.html

+1

All Articles