in reply to Question on Recursion

You're ignoring the result of the recursive call.
&spl($total) if ($len != 1);
should be
$total = &spl($total) if ($len != 1);

Now, what we have here what is called tail-end recursion. The recursion is the last thing in the function. That means you can use a loop instead.

sub spl { my ($num1) = @_; while (1) { my $total = 0; $total = $total + $_ for (split '', $num1); my $len = length ($total); if ($len == 1) { return $total; } $num1 = $total; } }

After some cleaning up, we get:

sub spl { my ($n) = @_; while (length($n) > 1) { my $total = 0; $total = $total + $_ for split '', $n; $n = $total; } return $n; }

or even

use List::Util qw( sum ); sub spl { my ($n) = @_; while (length($n) > 1) { $n = sum split '', $n; } return $n; }

Update: Added last snippet.

Replies are listed 'Best First'.
Re^2: Question on Recursion
by AnomalousMonk (Archbishop) on Jan 09, 2009 at 19:23 UTC
    FWIW: Yet another snippet, slightly different approach:
    >perl -wMstrict -le "sub T { my $n = 0; $n += $_ for @_; return $n <= 9 ? $n : T(split '', $n); } printf qq{%5s -> %d \n}, $_, T($_) for @ARGV " 1818 1819 1918 1500 5001 51 2300 0230 32 1 9 0 00 00000 10000 00001 1818 -> 9 1819 -> 1 1918 -> 1 1500 -> 6 5001 -> 6 51 -> 6 2300 -> 5 0230 -> 5 32 -> 5 1 -> 1 9 -> 9 0 -> 0 00 -> 0 00000 -> 0 10000 -> 1 00001 -> 1