prasadbabu has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks,
Today I wrote a small script for my friend to check the sum of the digits recursively (till single digit of length), numbers range from 1500 to 2300. For example:
Number 1818 1818 = 1+8+1+8 = 36 step 1 (2 digits output) 36 = 3 + 6 = 9 step 2 (single digit output) result: 9 (final count of the digits )
I wrote the below code and found the final total is printing continuously. I expected only 9 but it is printing both 9 and 18 continuously. I solved the issue later (case 2). But I want to know the reason why it is printing continuously 9 and 18. Because of that I am not getting final output '1818 == 9' in the main program.
I 'super searched' in perlmonks and found following links. subroutine recursion question,Recursion problem, Recursion. But I was not able to find correct answer. Even I googled but I didn't get correct answer. Even I flushed using $| but not able to get expected output. Where am I going wrong? Could someone explain where I am making mistake?
use strict; use warnings; my $total1; for my $num (1818..1818){ my $total1 = &spl($num); print "$num == 9\n" if ($total1 == 9); } ################# not working as i expected ####### case 1 sub spl{ my ($num1) = @_; my $total = 0; $total = $total + $_ for (split '', $num1); print "total: $total\n"; my $len = length ($total); print "length: $len\n"; &spl($total) if ($len != 1); print "final: $total\n"; return $total; } ########## working perfectly ######### case 2 #sub spl{ # #my ($num1) =@_; # #my $total = 0; # #$total = $total + $_ for (split '', $num1); # #my $len = length ($total); # #return $total if ($len == 1); # #&spl($total) if ($len != 1); # #} output: ------- total: 18 length: 2 total: 9 length: 1 final: 9 final: 18 Expected output: ---------------- total: 18 length: 2 total: 9 length: 1 final: 9 1818 == 9
Thanks in advance
Prasad
updated: added the line, 'Because of that I am not getting final output '1818 == 9' in the main program.'
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Question on Recursion
by ikegami (Patriarch) on Jan 09, 2009 at 11:06 UTC | |
by AnomalousMonk (Archbishop) on Jan 09, 2009 at 19:23 UTC | |
Re: Question on Recursion
by moritz (Cardinal) on Jan 09, 2009 at 11:07 UTC | |
Re: Question on Recursion
by JavaFan (Canon) on Jan 09, 2009 at 11:52 UTC | |
by roboticus (Chancellor) on Jan 09, 2009 at 13:23 UTC | |
by JavaFan (Canon) on Jan 09, 2009 at 13:26 UTC | |
by roboticus (Chancellor) on Jan 09, 2009 at 13:29 UTC |