Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: recursion basics

by sundialsvc4 (Abbot)
on Jun 23, 2015 at 12:57 UTC ( [id://1131620]=note: print w/replies, xml ) Need Help??


in reply to recursion basics

A useful way to see recursion in action is to add a variable to the function&rquo;s parameter list which is simply used to show the recursion nesting-level . . .

use strict; use warnings; sub foo { my $nesting_level = shift; print "Hello from level $nesting_level!\n"; if ($nesting_level < 3) { foo($nesting_level+1); } print "Goodbye from level $nesting_level!\n"; } foo(1); . . . gives . . . Hello from level 1! Hello from level 2! Hello from level 3! Goodbye from level 3! Goodbye from level 2! Goodbye from level 1!

The outermost call begins first but finishes last.   The innermost call, which does not “call itself,” of course finishes immediately.

This trivial example does not illustrate that each instance of the recursive function (like any instance of any function-call), has its own distinct set of local variables.

Replies are listed 'Best First'.
Re^2: recursion basics
by Your Mother (Archbishop) on Jun 27, 2015 at 02:35 UTC

    Thank you for posting working code. It is a clear example. I tweaked a little. Not comprehensive but indentation, as shown in previous examples from other monks, in particular is good for recursion examples, I think.

    sub foo { # 4 spaces or tab is standard. Why be different here? # Even this spotty arg check is better than none. my $nesting_level = shift || die "Nesting level needed!"; # Indentation is a great way to visualize recursion. my $indent = " " x ( $nesting_level - 1 ); print $indent, "Hello from level $nesting_level!\n"; # It's Perl, why not postfix? foo($nesting_level+1) if $nesting_level < 3; print $indent, "Goodbye from level $nesting_level!\n"; }
    Hello from level 1! Hello from level 2! Hello from level 3! Goodbye from level 3! Goodbye from level 2! Goodbye from level 1!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1131620]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-25 09:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found