Solved

# Hash Arithmetic

Posted on 2004-11-11
308 Views
Greetings Experts,

This is not a homework assignment.
I have a hash that has the following format
17asb345 1
17asb345 2
17asb345 5
17asb345 3
82dsic456 1
82dsic456 9
82dsic456 3
34xsw567 20
34xsw567 2
34xsw567 5

I want to calculate the net sum for the lines that start with the same string.

I have written the following, but would like code that is more efficient.

==begin code.pl
#!/usr/bin/perl

use strict;

my @newkeyArray;
my \$lkey;
my \$compkey;
my \$lcompkeyvalue;
my \$compkeyvalue;
my \$lkeyvalue;

foreach my \$newkeyArray (@newkeyArray) {
my (\$fkey,\$fkeyvalue) = split /\s/,\$newkeyArray;
\$compkey = \$fkey;
\$compkeyvalue = \$fkeyvalue;
if (\$fkey eq \$compkey) {
if (\$fkeyvalue > \$compkeyvalue) {
print "The \$fkeyvalue is greater >= \$compkeyvalue\n";
}
\$lcompkeyvalue = \$compkeyvalue;
}
\$compkeyvalue = \$fkeyvalue;
print "The first key is: \$fkey\n";
print "\$fkeyvalue\n";
\$lkey = \$compkey;
}
==end code.pl

0
Question by:uluttrell

LVL 7

Expert Comment

my @newkeyArray;
my %key_sum;
my %key_count;

map({my (\$k,\$v)=split(/\s/);\$key_sum{\$k}+=\$v;\$key_count{\$k}++} @newkeyArray);

for (keys(%key_count)){
print "key=\$_ sum=\$key_sum{\$_}\n" if(\$key_count{\$_} > 1);
}
0

LVL 18

Expert Comment

foreach (@newKeyArray) {
\$sums{\$1} += \$2 if /^(\w+)\s+(\d+)/;
}
0

Author Comment

rugdog, if the has has odd elements such as this:
17asb345 1
17asb345 2
17asb345 5
17asb345 3
82dsic456 1
82dsic456 9
82dsic456 3
34xsw567 20
34xsw567 2
34xsw567 5
52wox678 10

The script does not yield a value for 52wox678.  How do you account for that?
0

LVL 7

Accepted Solution

well since you asked the script to print the sum of  lines with the same key, the one I wrote, will print only the keys that are repeated, to print all keys sums:

my @newkeyArray;
my %key_sum;

map({my (\$k,\$v)=split(/\s/);\$key_sum{\$k}+=\$v;} @newkeyArray);

for (keys(%key_sum)){
print "key=\$_ sum=\$key_sum{\$_}\n";
}
0

Author Comment

rugdog, sorry for changing directions on you.  The change works great.  Thank you.
0

LVL 7

Expert Comment

you're welcome
0

## Featured Post

There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…