erabus has asked for the wisdom of the Perl Monks concerning the following question:

Is there a way to unwind the call stack and return a value? I am writing an exception handler for fatal error conditions. Instead of calling die I would like to rewind the stack to main. Is there a function or module that provides this capability? Can I return a string to main? Thanks.
  • Comment on Is there a way to unwind the call stack and return a value?

Replies are listed 'Best First'.
Re: Is there a way to unwind the call stack and return a value?
by Fletch (Bishop) on Mar 21, 2008 at 21:56 UTC

    Erm, caller isn't going to do you much good unwinding the call stack (figuring out where in the stack you are, yes; manipulating it, no).

    As has been pointed out eval and die are Perl for try and throw. If you're looking for something more oop-y perhaps something like Exception::Class (mentioned here very recently) would serve?

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Is there a way to unwind the call stack and return a value?
by Joost (Canon) on Mar 21, 2008 at 21:43 UTC
Re: Is there a way to unwind the call stack and return a value?
by ikegami (Patriarch) on Mar 21, 2008 at 22:12 UTC
    A demonstration:
    sub baz { my $data = "something"; # Doesn't have to be a string die($data); } sub bar { baz(); } sub foo { bar(); } #main if (!eval { foo(); 1 }) { print("Got data from deep function: $@"); }
Re: Is there a way to unwind the call stack and return a value?
by GrandFather (Saint) on Mar 22, 2008 at 21:34 UTC

    I suspect what you are asking for is to be able to return the point of execution to the state that pertained just before the exception was thrown, but with conditions altered to avoid the throw. You would need a modified die to achieve that which calls error handling at the point of failure and is capable of rerunning the failing statement following the return from the handler.

    While such an animal may be possible (most processors handle math exceptions and memory issues that way), it's non-trivial in an arbitrary context and would probably require fiddling with Perl's internals. You would be much better to rethink your error handling to avoid the problem - perhaps by wrapping a sub in an eval block and retrying the sub on error?


    Perl is environmentally friendly - it saves trees