[comp.lang.perl] for loop bug

maart@cs.vu.nl (Maarten Litmaath) (12/14/90)

The following code makes perl PL41 dump core on a Sun4 running SunOS 4.0.3c:

--------------------cut here--------------------
sub pipo {
	local($x) = @_;
	local($i);
	if ($x > 2) {
		return;
	}
	for $i (1..5) {
		print "i=$i x=$x\n";
		&pipo($x + 1);
		print "\ti=$i x=$x\n";
	}
}

&pipo(0);
--------------------cut here--------------------

Tom Christiansen already discovered (paraphrasing) ``that the foreach
iterator isn't getting properly fixed up for when you recurse.''
He also noticed: ``If you make it a literal array, it works fine.''
This is illustrated in the following example:

--------------------cut here--------------------
sub pipo {
	local($x) = @_;
	local($i);
	local(@L) = 1..5;

	if ($x > 2) {
		return;
	}
	for $i (@L) {
		print "i=$i x=$x\n";
		&pipo($x + 1);
		print "\ti=$i x=$x\n";
	}
}

&pipo(0);
--------------------cut here--------------------

Oh, in case anyone wonders about the name of the subroutine: `Pipo' is a
famous Dutch clown.  So `pipo' is the Dutch variant of `foo' for temporary
files, variables, etc.  Another common name: `aap' == monkey/ape.
This free extra piece of information was brought to you by the Usenet
electrons.
--
In the Bourne shell syntax tabs and spaces are equivalent almost everywhere.
The exception: _indented_ here documents.  :-(
Does anyone remember the famous mistake Makefile-novices often make?