Monks,

The first example code of HOP is something like this (I added print statements):
sub binary { my ($n) = @_; return $n if $n == 0 || $n == 1; my $k = int($n/2); my $b = $n % 2; print "n is $n.\nk is $k.\nb is $b.\n"; print "above\n"; my $E = binary($k); print "below\n"; print "n is $n.\nE is $E.\n\n"; return $E . $b; } print binary(8);
And the output:
n is 8. k is 4. b is 0. above n is 4. k is 2. b is 0. above n is 2. k is 1. b is 0. above below n is 2. E is 1. below n is 4. E is 10. below n is 8. E is 100. 1000
The program "loops" 3 times before the final return. Obviously it is not a simple loop, though, and that is what confuses me. I don't understand the recursion process. I naively expect above/below above/below above/below return sequence, rather than above/above/above below/below/below return.

UPDATE: And notice the sequence of "n" value is an inside-out sequence. What?

I'm not seeing this, please help me understand. Thanks.

UPDATE 2: Thanks to all Monks for your generous and informative replies. PerlMonks is certainly the best resource for information in the Perl Community.

In reply to recursion basics by wrinkles

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.