Divide and add numbers

If I open a file with lines like "233445", how can I divide this line into numbers "2 3 3 4 4 5" and add to each other "2 + 3 + 3, etc."? and print the result.

My code 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 do not know where to start for the add function.

+4
source share
4 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; use strict; use warnings; . It would detect your misuse of commas in qw , and that would negate the misuse of undef to split first argument.

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

No one suggested an eval solution?

 my @strings = qw( 12243434 345 676744 ); foreach my $string (@strings) { my $sum = eval join '+',split //, $string; print "$sum\n"; } 
+2
source

If your numbers are in a file, a single line can be nice:

 perl -lnwe 'my $sum; s/(\d)/$sum += $1/eg; print $sum' numbers.txt 

Since adding uses only numbers, it is safe to ignore all other characters. So just extract them one at a time with the regular expression and sum them up.

TIMTOWTDI:

 perl -MList::Util=sum -lnwe 'print sum(/\d/g);' numbers.txt perl -lnwe 'my $a; $a+=$_ for /\d/g; print $a' numbers.txt 

Parameters:

  • -l enter auto-chomp and add a new line to print
  • -n implicit while(<>) loop around the program - open the file name specified as an argument and read each line in $_ .
+1
source

Source: https://habr.com/ru/post/1394488/


All Articles