in reply to Re: Make calculation with values from hash
in thread Make calculation with values from hash

testdata C 25.00 D 40.20 testdata2 D 79.00 C 25.00
hi wfsp, thanks for your reply. Without making a change to the code the above is what I get as result. Which I'm pretty happy with. Next step though is to do something like: C -/-  Dfor all files (testdata..) and then take the total from this at the bottom of the report.
My problem is how to get to substract 25 minus 40.20. How to refer to this data?

Replies are listed 'Best First'.
Re^3: Make calculation with values from hash
by almut (Canon) on Jan 02, 2007 at 21:30 UTC
    My problem is how to get to substract 25 minus 40.20. How to refer to this data?

    If I'm understanding you correctly, that would be

    my $diff = $saldi{C} - $saldi{D};
    However, looking at the rest of the fine code you've produced already (no irony!), makes me think this can't really be your problem... :)

    So, let me guess, the problem is you want to access the values at a point in your program where they're no longer available, e.g. after having completed the foreach $file ( glob "*.txt" ) { ... } loop(?)

    In that case - if you want grand totals over all data files - you'll simply have to move the %saldi hash before the outer loop, as already suggested by wfsp -- as you have things now, %saldi will (a) get reinitialised for every new file (so the old values are lost), (b) fall out of scope when the loop is done (also meaning the values are lost).

    Otherwise - if you want to keep individual sums per file - you'd have to store those values away in a somewhat more complex data structure, e.g. a hash-of-hashes (HoH). Something like that:

    my %saldi; foreach $file ( glob "*.txt" ) { open FILE, '<', $file; my $data = {}; while (<FILE>) { chomp; next unless /\S/; my ($name, $price) = ( split /,/, )[ 3, 4 ]; next unless $name && $price; $data->{$name} += $price; } my ($datasetname) = $file =~ m/^(\S+)\.txt/; print "$datasetname\n"; foreach my $name ( keys %$data ) { printf "\t$name\t" . "%16s\n", big_money( $data->{$name} ); } # store it... $saldi{$datasetname} = $data; close FILE; } # now, you can access all data by specifying the appropriate # pairs of keys, e.g. printf "diff C-D: %.2f\n", $saldi{testdata}{C} - $saldi{testdata}{D}; # ...

    HTH :)