gopikavi has asked for the wisdom of the Perl Monks concerning the following question:

%namesum; open $f,"<data.txt" or die $!; while ($line=<$f>) { chomp $line; next unless $line; $line=~s/[\{\}]//g; @parts=split(/\s+/,$line); ($input1,$input2)=split('/',$parts[2]); $name=substr($parts[0],0,11); $namesum{$name}[0]+=$input1; $namesum{$name}[1]+=$input2; $output=$namesum{$name}[1]-$namesum{$name}[0]; } for $key (sort keys %namesum){ print "\nname:".$key."\n"; print .$namesum{$key}[0]."\n"; print .$namesum{$key}[1]."\n"; print .$output."\n"; }
In the above code the output fails to subtract the $input1 and $input2 variables
obtained output
name:data1 11 12 12
Expected name :data1 11 12 1

Replies are listed 'Best First'.
Re: how to subtract storage of hashes using perl?
by poj (Abbot) on May 09, 2017 at 06:16 UTC
    the output fails to subtract the $input1 and $input2 variables

    Put the calculation of $output in the second loop.

    #!/usr/bin/perl use strict; #use Data::Dump 'pp'; my %namesum = (); #open my $fh,'<','data.txt' or die $!; #while (my $line=<$fh>) { while (my $line = <DATA>){ chomp $line; next unless $line; $line =~ s/[\{\}]//g; my @parts = split /\s+/,$line; my $name = substr($parts[0],0,11); my @input = split '/',$parts[2]; $namesum{$name}[0] += $input[0]; $namesum{$name}[1] += $input[1]; } #pp \%namesum; for my $key (sort keys %namesum){ my $output = $namesum{$key}[1] - $namesum{$key}[0]; print "name:"; print join "\t",$key ,$namesum{$key}[0] ,$namesum{$key}[1] ,$output."\n"; } __DATA__ {name1 1 2/3} {name2 4 5/6}
    poj