Tuesday, March 26, 2013

Perl - How to find the sum of digits in a number?



How to find the sum of all the digits in a number or a string? OR How to find the sum of all elements in array? Let us see the different ways how it can be done in Perl?

1. Divide and accumulate:
my $x=3456;
my $sum=0;
while ($x) {
        $sum+=$x%10;
        $x/=10;
}
print $sum;
  The digits are extracted by taking the modulus of the number with 10, and then dividing the number by 10. This is repeated till the original number becomes zero at the end of which the sum is retrieved.

2. Using regular expression:
my $x=3456;
my @arr=$x=~/./g;
my $sum=0;
$sum+=$_ foreach(@arr);
print $sum;
  The number is broken into individual digits using the regular expression and extracted into an array. The array elements are looped using the foreach loop and the sum is calculated.

3. Using eval and join:
my $x=3456;
my @arr=$x=~/./g;
print eval join "+",@arr;
 The number is separated into digits as in the last example. Using join, all the digits are joined using "+" and then the eval function evaluates the string.

4. Using CPAN module List::Util:
use List::Util qw(sum);

my $x=3456;
my @arr=$x=~/./g;
print sum @arr;
  The CPAN module List::Util contains a subroutine sum which takes an array as input and calculates the returns sum of all elements in the array.
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment