in reply to Re: sub calls and memory use
in thread sub calls and memory use

What if you need to pass an arg to the sub? Even empty parens with goto cause memory growth. I got around it by changing a global var instead of passing args but is there a more proper way? Thanx

Replies are listed 'Best First'.
Re^3: sub calls and memory use
by Corion (Patriarch) on Nov 16, 2019 at 14:17 UTC

    See goto. You pass arguments in @_, as always.

    Of course, when calling any function, the call stack still grows since the return address needs to be stored on the call stack. This is independent of any function parameters (or none) passed to the next recursive invocation.

    Update: As the replies below also point out, I answered too quickly. I thought you were still calling the function but with empty parameters. If you're using goto to transfer control to the function, there should be no memory growth, as the replies also say.

      > the call stack still grows since the return address needs to be stored on the call stack.

      I'm pretty sure that this is not needed because you can't return to the source of a goto.

      If it's stored nevertheless than it's for vain.

      But I really doubt this because the docs clearly say that even caller can't tell where the call happened.

      IMHO goto &sub was never optimized to allow tail call optimizations, it's main purpose is the use in AUTOLOAD.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

        I'm pretty sure that this is not needed because you can't return to the source of a goto
        Indeed, goto &foo pops the current call frame and replaces it with a new frame, rather than just pushing an additional one as a normal sub call would do. The following consumes lots of CPU but uses constant memory:
        sub foo { goto &foo }; foo();

        Dave.

      You pass arguments in @_, as always.

      So I was just using the wrong global variable! I can see now that pushing my arg into @_ before the &sub call prevents memory growth. Thank you Corion.

        In Perl you are generally better off translating tail calls to loops. They are way faster and easier to understand.

        You never explained your use case, but your example is easily translated with redo

        Concerning your memory growth, we'd need to know how you declared the "global var".

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery FootballPerl is like chess, only without the dice