Reputation: 441
I am trying to make a Perl script that goes through and loops through a file, does some Regex to get number that are surrounded by parenthesis, add them up for every line.
#file
Awaiting_Parts_Bin(2),Inspection_Bin(1),Picked-1-3888(1),Picked-1-4364(2)
Picked-1-3890(1)
Picked-1-4364(1)
Picked-1-3888(4),Picked-1-3890(2),Picked-1-4364(1),Picked-1-7202(1)
Awaiting_Parts_Bin(1)
Desired Output
#new_file
6
1
1
8
1
Perl script
#!/usr/bin/perl
use strict;
use warnings;
my $file = '/Users/.....csv';
my $new_file = '/Users/.....csv';
open(my $fh, '<', $file)
or die "cannot open file";
open(my $new_fh, '>', $new_file)
or die "cannot open file";
my $sum = 0;
while (my $line = <$fh>){
my @arr = ( $line =~ /\(([0-9]+)\)/g);
foreach my $val ( @arr ) {
$sum += $val;
print $sum, "\n";
# this makes sense that it is resetting to zero while looping. This is just one variation I tried. I tried putting the sum=0 outside the loop and it made it a running total
$sum = 0;
}
}
No matter what I try I can't get it right. This code doesn't add all of the values it takes the last one in the file. So the output would look like this
#output now
2
1
1
1
1
Or if I remove the $sum=0
in the for loop then it makes it a running total.
Upvotes: 2
Views: 166
Reputation: 126722
Like this?
use strict;
use warnings 'all';
use List::Util 'sum';
while ( <> ) {
my $sum = sum /\((\d+)\)/g;
print "$sum\n" if defined $sum;
}
6
1
1
8
1
Upvotes: 2
Reputation: 339816
You need to reset $sum
to zero at the start of the outer (per line) while
loop, not in the inner (per element) foreach
loop.
This can be achieved by putting the declaration and initial assignment of $sum
inside the while
loop:
while (my $line = <$fh>) {
my $sum = 0;
my @arr = ( $line =~ /\(([0-9]+)\)/g);
foreach my $val ( @arr ) {
$sum += $val;
}
print $sum, "\n";
}
Upvotes: 4