http://qs321.pair.com?node_id=870420

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

Why isn't goto &NAME working within an eval? For example, the following code snippet never seems to enter foo2().
foo( "a" ); sub foo { eval { goto &foo2; }; } sub foo2 { print "foo2 called with @_\n"; }
If you leave out the eval, it starts working.

Replies are listed 'Best First'.
Re: eval and goto: no worky?
by ikegami (Patriarch) on Nov 09, 2010 at 22:57 UTC

    Perl tells you "Can't goto subroutine from an eval-block".

    You ask Perl to catch errors, then you ask Perl to replace the currently running function with another, but it can't continue to catch errors if it's no longer running. Given conflicting instructions, Perl lets you know you have something to fix.

    Update: Substituted the explanation with a much clearer version.

      Interesting, I didn't see a warning with warnings and strict on. Did you find that in the documentation?
        foo( "a" ); sub foo { eval { goto &foo2; } or warn $@; } sub foo2 { print "foo2 called with @_\n"; } __END__ Can't goto subroutine from an eval-block at - line 4.
        It's not a warning, it's a fatal error. You successfully caught the error and subsequently ignored it. An Anonymous Monk shows how you could actually look at the error you are hiding.
Re: eval and goto: no worky?
by BrowserUk (Patriarch) on Nov 09, 2010 at 23:22 UTC

    There is no need to use eval with goto:

    sub f1{ print 'f1'} sub f2{ print 'f2' } sub f{ goto &{$_[0]} };; f('f1');; f1 f('f2');; f2 f('f');; ### Warning infinite loop!

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Actually, my goal was to define a wrapper function that could never die(), even if the inner function did and expose this new interface to the user.

      The advantage of using 'goto' would have been that the caller level in the inner function would have been unchanged, but I worked around the Perl limitation of not offering goto &NAME with eval {} by adding some code to adapt the caller level manually at the application level.

      Thanks, all!