in reply to Question on using format and write

foreach $key (sort keys %ytd ){ ... 
No strict? ... watch out for the Inquisitors! I'll presume that you declared $key earlier. ;)

Seriously, i want to point out that anytime i see variables like $t1, $c1, ,$d1, etc., i try to remove these and use 'containers' instead. Here is my take on the problem:

use strict; my (@stuff,$cust,$total); my %ytd = ( foo => { d1 => 1, d2 => 2, c1 => 3, c2 => 4 }, bar => { d1 => 5, d2 => 6, c1 => 7, c2 => 8 }, baz => { d1 => 9, d2 => 1, c1 => 2, c2 => 3 }, qux => { d1 => 4, d2 => 5, c1 => 2, c2 => 4 }, ); foreach $cust (sort keys %ytd) { my @tot = map { $ytd{$cust}->{"d$_"} - $ytd{$cust}->{"c$_"} } 1..2; $total = do { my $t; $t += $_ for @tot; $t }; @stuff = ( $ytd{$cust}->{d1}, $ytd{$cust}->{c1}, $tot[0], $ytd{$cust}->{d2}, $ytd{$cust}->{c2}, $tot[1], ); write; } format STDOUT = @<<<<<<<<<<<<<<<<<<<< $cust @#####.## @#####.## @#####.## @#####.## @#####.## @#####.## @stuff @#####.## $total .
I think that shoving the number items into an array is more convenient and allows you to use the array in the format instead of the individual scalars.

Without knowing the problem, i can't really comment on your datastructure %ytd, but it might benefit you in terms of maintenance to combine each of the 'dN' and 'cN' pairs into one that contains an array. For example:

my %ytd = ( foo => { d => [1,2], c => [3,4] }, bar => { d => [5,6], c => [7,8] }, baz => { d => [9,1], c => [2,3] }, qux => { d => [4,5], c => [2,4] }, );
Just food for thought. :)

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: (jeffa) Re: Question on using format and write
by Popcorn Dave (Abbot) on Dec 13, 2002 at 23:05 UTC
    Ah yes, use strict is there, just not in the snippet I posted. Sort of like American Express, I don't code without it. : )

    My data structure is two flat files with customer names and data. The names should match in both files, but I've got to get the data from the two files in to a structure indexed by customer name. The files generated and ascii is my best option.

    I've got it working at present, but I agree the code is messy at best. I am quite intrigued by your array idea and will try that approach instead. Thanks!

    There is no emoticon for what I'm feeling now.