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.

Thursday, March 14, 2013

How to remove leading zeros in a string in Linux?

How to remove leading zeros in a variable or a string?

Let us consider a variable "x" which has the below value :
$ x=0010
$ echo $x
0010
1. Using typeset command of ksh:
$ typeset -LZ x
$ x=0010
$ echo $x
10
   The variable x is declared using the typeset command. The -Z option of typeset will strip the leading zeros present when used along with -L option.