in reply to Re^2: Make calculation with values from hash
in thread Make calculation with values from hash
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
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... :)my $diff = $saldi{C} - $saldi{D};
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 :)
|
|---|