Sridhar-Sarnobat Sridhar-Sarnobat - 1 year ago 178
Perl Question

Perl accumulator array for implicit loop one liner? (to perform a sql-like 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}'


Remember, in non-strict mode you don't need to declare any variables including arrays. You can just use them as the accepted answer indicates.

Answer Source

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 { for $d (sort keys %tot) { print "$d\t\$$tot{$d}" } }' mydata.csv

The disadvantage here is you have to handle the dollar sign, both stripping it out an adding it back in.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download