I have to hack some reports together with running totals. I was wondering if there was some efficient way of accumulating fields in an upward-compatible manner -- that is, should I have to add another column I have to change as little code as possible.
I was wondering if I could coax += into being distributive across a hash slice, so I could do the following:
#! /usr/bin/perl -w use strict; my( %totals, %delta ); my @fields = qw/foo bar/; @totals{ @fields } = ( 10, 20 ); @delta{ @fields } = ( 5, 6 ); # the wish # @totals{ @fields } += @delta{ @fields }; # the reality $totals{$_} += $delta{$_} foreach( @fields ); use Data::Dumper; print Dumper( \%totals );
Of course in both cases the code is not dependent on the exact fields used, so the main goal has been achieved, but I find the reality code a little ugly. I was wondering if there was some other elegant method of doing this that escapes me. The fields are already in a hash, as I am using DBI's fetchrow_hashref.
In reply to Using += in array context by grinder
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |