in reply to Entering and exiting subs in style

That goto discussion seems to be saying that goto a subroutine ought only to be used in the most magical circumstances.

Surely it would render your code completely unreadable, anyway. The return from the sub would take you where? It's not immediately obvious to me, so I wouldn't use it.

I've only ever used goto once in perl, I forget what my reasoning was, but very shortly after I substituted it for something else (better?).

Replies are listed 'Best First'.
Re: Re: Entering and exiting subs in style
by rinceWind (Monsignor) on May 26, 2004 at 14:02 UTC
    That goto discussion seems to be saying that goto a subroutine ought only to be used in the most magical circumstances.
    More to the point is to consider exactly when you would need to use it, and when you care. The circumstances are when you want to fake "caller" to the sub being called, i.e. make your current subroutine invisible.

    One circumstance when you would do this is in an AUTOLOAD subroutine that is generating new subroutines on the hoof (or loading them in from files). Suppose we have a package Foo and function bar, which does not exist at the start of the program. The first call to Foo::bar results in a call to Foo::AUTOLOAD, with $Foo::AUTOLOAD set to 'Foo::bar'.

    The AUTOLOAD code creates a new subroutine and puts it into package name space as Foo::bar, so future calls to Foo::bar call this sub directly. We want the first call to Foo::bar not to see its caller as Foo::AUTOLOAD, but as the real caller. In order to achieve this, AUTOLOAD does a goto &Foo::bar once it has finished.

    Other times when you might need to fake "caller" are more arcane, such as what Hook::LexWrap does internally. You also need to use these techniques if you are writing a debugger, profiler or such like.

    Hopefully this has explained the "magic" in this case.

    --
    I'm Not Just Another Perl Hacker

Re: Re: Entering and exiting subs in style
by Joost (Canon) on May 26, 2004 at 21:48 UTC
    I've used goto &sub in some state-machines, just because I didn't want the overhead of creating a larger stack that I'm not intending to use anyway.

    This means that you go from one sub to the other without being able to return back to the first sub - if you return, you go back to the "original caller", which in this case was exactly what I wanted, and it can save some memory that otherwise is being used to store the lexicals in the stack of subs.(AFAIK this is related to tail recursion).

    As far as the OP is concerned, I'd recommend using die, as suggested above.