recursion

Darren Duncan darren at DarrenDuncan.net
Thu Jan 30 16:04:38 CST 2003


Essentially, recursion is where a method or function calls itself.  If
this is done without conditions, it is like an endless loop, except this
one will cause you to run out of memory quickly.  So all recursive
functions that work take arguments, and when that function calls itself,
it calls itself with a different argument than it was called with itself;
a simple example is to take its own argument and subtract one, and call
itself with the result.  Moreover, the call to itself is always
conditional, such as if the passed number is less than or equal to zero,
then don't call itself.

This is a perl version of the Java example:

On Thu, 30 Jan 2003, nkuipers wrote:
> method printme with arg int
> if int not equal to 0 { printme (int-1) }
> print int

sub printme {
	my ($int) = @_;
	$int <= 0 or printme( $int-1 );
	print $int;
}

Note that the call to itself happens before the print, which means that
the last call to printme prints first, with subsequently earlier ones
printing next.  Hence, if the function is first called with a '7', then
that 7 is the last value to be printed.

If you want a good example of where recursion is actually useful, try
writing a simple Perl function which takes a reference to an arbitrarily
complex multi-dimensional Perl data structure as an input and outputs a
serialized representation, such as a string that can be eval'd to produce
the original data structure.  I have written one that handles scalars,
arrays, and hashes, properly differentiating undef, and it is less than 10
lines long (pretty-printed).

When you have done, post your resulting function on this list, and I'll do
mine.

-- Darren Duncan




More information about the Victoria-pm mailing list