in reply to Make calculation with values from hash

Hi GertMT!

I think you need to move the second foreach loop outside of the first foreach loop. You need to move my %saldi; to before the first foreach loop.

I get (unformatted):

C 50.00 D 119.20
Is that something like what you're after?

Let us know how you get on.

Replies are listed 'Best First'.
Re^2: Make calculation with values from hash
by GertMT (Hermit) on Jan 02, 2007 at 19:08 UTC
    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?
      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 :)