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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With