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 |