Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split and add digits

Tags:

math

perl

If I open a file with strings like "233445", how can I then split that string into digits "2 3 3 4 4 5" and add each one to each other "2 + 3 + 3 etc..." and print out the result.

My code so far looks like this:

use strict;

#open (FILE, '<', shift);
#my @strings = <FILE>;
@strings = qw(12243434, 345, 676744); ## or a contents of a file
foreach my $numbers (@strings) {
   my @done = split(undef, $numbers);
   print "@done\n";
}

But I don't know where to start for the actual add function.

like image 248
Daveid Fred Avatar asked Dec 13 '22 05:12

Daveid Fred


1 Answers

use strict;
use warnings;

my @strings = qw( 12243434 345 676744 );
for my $string (@strings) {
   my $sum;
   $sum += $_ for split(//, $string);
   print "$sum\n";
}

or

use strict;
use warnings;
use List::Util qw( sum );

my @strings = qw( 12243434 345 676744 );
for my $string (@strings) {
   my $sum = sum split(//, $string);
   print "$sum\n";
}

PS — Always use use strict; use warnings;. It would have detected your misuse of commas in qw, and it would have dected your misuse of undef for split's first argument.

like image 74
ikegami Avatar answered Jan 06 '23 21:01

ikegami