in reply to recursion basics

Hopefully, the next few statements will make sense when read slowly.:

The (recursive) call to binary() occurs between the "print ABOVE" and "print BELOW"

This means that before the BELOW gets printed, the sub is called again, going through he "ABOVE" logic.

This causes ABOVE to be printed again .. and again on each recursive call, not giving BELOW a chance until the recursion completes.

Now - the RECURSED instance also goes through the same steps, and is unable to print BELOW until the NEXT recursion completes.

So, the "BELOW"s stack up and are released together as the recursion unwinds.

If you use the perl "-d" switch, you can step through the recursion, and even do a "T" stack trace to see what the sequence is.

        "Despite my privileged upbringing, I'm actually quite well-balanced. I have a chip on both shoulders."         - John Nash

Replies are listed 'Best First'.
Re^2: recursion basics
by wrinkles (Pilgrim) on Jun 23, 2015 at 06:35 UTC
    Even slow that's a challenge. Why does the final return only run once? I mean, why doesn't the return interrupt the unwinding earlier?

      Check my first reply for a more detailed explanation, but the short version is that, each time the function calls itself, the caller stops and waits for the "child" function to finish. So none of the instances reach that final return until one of them returns from the first return, then they all finish and hit the second return in reverse order. Something like this:

      binary1 calls binary2, stops and waits for it binary2 calls binary3, stops and waits for it binary3 calls binary4, stops and waits for it binary4 returns from the first return line ($n==1) binary3 finishes, returns binary2 finishes, returns binary1 finishes, returns print statement executes, printing binary1's return value

      Aaron B.
      Available for small or large Perl jobs and *nix system administration; see my home node.

      Read my post here. Hopefully, it should make it clear to you.

      Even slow that's a challenge. Why does the final return only run once? I mean, why doesn't the return interrupt the unwinding earlier?

      Um, try this, and ask yourself what happens

      Rip(); sub Rip { print "Rip on\n"; Van(); Winkle(); print "Rip off\n"; } sub Van { print "Van on\n"; Winkle(); print "Van off\n"; } sub Winkle { print "Winkle\n"; } __END__ Rip on Van on Winkle Van off Winkle Rip off