I have to admit, for a while you had me stumped. But then I realized that this code is not correct:
$accounts{'total'} = 0; # here you add a key to the serverlist
foreach my $server1 (keys %accounts) { # here you list all keys
$accounts{'total'} = $accounts{'total'} + $accounts{$server1};
print "\nAdded $accounts{$server1} and total is now $accounts{'total'}";
}
Because the key total
is one of the keys in the same hash:
titus.zimbra.h.bitbit.net
tiberius.zimbra.h.bitbit.net
otho.zimbra.h.bitbit.net
total
So when you reach the point in the list for key total
, you see that the total doubles, from 794 to 1588.
The answer would be to not use the same hash for storing your sum. In fact, why use a hash at all?
my $total = 0; # independent scalar
foreach my $server1 (keys %accounts) {
$total += $accounts{$server1};
print "\nAdded $accounts{$server1} and total is now $total";
}
Also worth noting is that you say in the comments that chomp
turns all your numbers into 1. You are probably using chomp
wrong, which is a common beginner mistake.
$count = chomp($count); # WRONG! chomp returns number of newlines removed
chomp($count); # Correct. chomp modifies its argument variable
You might ask what good it is for chomp
to return the number of newlines removed, and the answer is that it can also be used on arrays and hashes:
my $removed = chomp(@array); # See how many newlines were removed