in reply to Tail Recursion "Optimising" with goto &sub

This idea had been brewing a while when I found a wiki page saying that it couldn't be done in perl.

Now couldn't can be changed to wouldn't.

Note that since the subs use the same @_ the guardian sub needs to copy it. Then the values can be modified.

For more code and avoidance of the recursion warning, readmore

Here's some interesting output, the script follows:
$ ./t.pl 
f_tail_rec(100) = 9.33262154439442e+157
--------------------
Deep recursion on subroutine "main::f_normal_rec" at ./t.pl line 30.
f_normal_rec(100) = 9.33262154439441e+157
#!/usr/bin/perl -w # http://c2.com/cgi/wiki?TailCallOptimization use strict; use Carp qw(cluck); my $cluck = 0; sub _f_tail_rec { if($_[0] == 0) { cluck "Goto optimized stack trace" if $cluck; return $_[1] } $_[1] *= $_[0]; $_[0]--; goto &_f_tail_rec; } sub f_tail_rec { @_ = (@_, 1); goto &_f_tail_rec;} my $n = 100; print "f_tail_rec($n) = ".f_tail_rec($n),"\n"; print "-"x20,"\n"; print "f_normal_rec($n) = ".f_normal_rec($n),"\n"; sub f_normal_rec { if($_[0] == 0) { cluck "Recursion stack trace" if $cluck; return 1; } return $_[0] * f_normal_rec($_[0]-1); }