in reply to sub calls and memory use

The call stack grows.

Perl does not implement "tail call optimization" automatically.

If you want this, you need to do it manually, by using goto:

$|++; re(); sub re { print '.'; select undef,undef,undef,0.01; goto &re; }

or

use 5.016; $|++; re(); sub re { print '.'; select undef,undef,undef,0.01; goto __SUB__; }

Replies are listed 'Best First'.
Re^2: sub calls and memory use
by LanX (Saint) on Nov 16, 2019 at 12:38 UTC
    Addendum: NB: like this any extra return will now jump directly to the first call, because of the bypassing of the call stack.

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

    update

    Reworded

Re^2: sub calls and memory use
by Anonymous Monk on Nov 16, 2019 at 14:06 UTC
    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

      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

        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.