grinder has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using += in array context
by Abigail (Deacon) on Jun 05, 2001 at 20:11 UTC | |
by bikeNomad (Priest) on Jun 05, 2001 at 21:12 UTC | |
|
Re: Using += in array context
by Spudnuts (Pilgrim) on Jun 05, 2001 at 18:18 UTC | |
|
Re: Using += in array context
by jeroenes (Priest) on Jun 05, 2001 at 18:18 UTC | |
|
Re: Using += in array context
by Henri Icarus (Beadle) on Jun 05, 2001 at 17:53 UTC | |
by tye (Sage) on Jun 05, 2001 at 18:32 UTC | |
|
Re: Using += in array context
by toma (Vicar) on Jun 05, 2001 at 20:32 UTC | |
|
Re: Using += in array context
by bikeNomad (Priest) on Jun 05, 2001 at 19:58 UTC | |
|
Re: Using += in array context
by mattr (Curate) on Jun 06, 2001 at 11:15 UTC |