#*A small script to check the sum of a number's digits recursively (until single digit of length). #p This unnamed module begins the perl source. use strict; use warnings; #
# # The Main Program. Here we define the main program. We declare a variable, |$total1|, to handle the value returned from the subroutine |sub1|. In this example version of the program we are only going to exam the number 1818 to demonstrate that we get the correct result of 9. If we do get this result than we |print| a confirmation. Note also the use of |perlWEB|'s macro ability. #d TEST_NUMBER=1818 #
= my $tota11; for my $num (TEST_NUMBER..TEST_NUMBER){ my $tota11 = &spl($num); print "$num == 9\n" if ($tota11 == 9); } # The subroutine that handles all of the essential computation. The algorithm is as follows:
• |$total|=the sum of the digits of what is expected to be the sole(or first) argument to |sp1|
• if |$total| has 1 digit then print it out
otherwise…
• call |sp1| again with |$total| as the argument #= sub spl{ my ($num1) =@_; #we can still have inline comments as well. my $total = 0; $total = $total + $_ for (split '', $num1);#here $total is #the sum of all the digits of $num1 my $len = length ($total); return $total if ($len == 1); &spl($total) if ($len != 1); } #### use strict; use warnings; my $tota11; for my $num (1818..1818){ my $tota11 = &spl($num); print "$num == 9\n" if ($tota11 == 9); } sub spl{ my ($num1) =@_; #we can still have inline comments as well. my $total = 0; $total = $total + $_ for (split '', $num1);#here $total is the #sum of all the digits of $num1 my $len = length ($total); return $total if ($len == 1); &spl($total) if ($len != 1); }