Sridhar-Sarnobat Sridhar-Sarnobat - 9 months ago 51
Perl Question

Perl accumulator array for one liner? (to perform a group by sum)

I want to sum the following data, grouped by month (my Amazon spending aggregated by month):


2016-08 $5
2016-08 $10
2016-09 $7
2016-09 $6
2016-10 $7
2016-10 $5


2016-08 $15
2016-09 $13
2016-10 $12

and I've seen a lot of ugly solutions on the web. I want to use the
perl -pe
syntax like I would for regex substitutions (i.e. implicit loop).

Can this be done, perhaps with an "implicit variable" that is an array?

I imagine the command to be something like this:

cat mydata.csv | perl -pe 's{(.*)\s*(.*)}{dict[$1] = $1 , dict[$1] += $2 }ge END { print @dict}'


I don't know if this is any better than what you have, but you can use Perl in the same way you use AWK and refer to the fields in @F:

perl -alne '$F[1]=~tr/$//d; $tot{$F[0]} += $F[1];
   END { while (($d,$t) = each %tot) { print "$d\t\$$t\n" } }' mydata.csv

The disadvantage here is you have to handle the dollar sign, both stripping it out an adding it back in. Also, because it's a hash, it won't order the way you want to, but you can add a | sort at the end to take care of that or order your output with a foreach instead of a while.