Good question. Hashes are a source of vague confusion to many programmers (some of whom I've worked with, particularly C++ programmers, treat them with rather a reverence bordering on mysticism).
First, rearrange your lines to put the chomp BEFORE any code that references $_. This way the value returned from split(), which is being assigned to $value won't end in a newline ("\n").
Then, assign the VALUE (in $value) to the hash indexed by $key. Your code associates $key with itself, not with $value.
Also, note that split /;/; is IDENTICAL to what you have, split(/;/, $_); but is more succinct (once you're accustomed to Perl idioms).
while (<OUTFILE>) { chomp; # <== move the chomp here my ($key, $value) = split /;/; $calhash{$key} = $value; # not '= $key' }
That addresses the hash loading issues.
Your printing code is fine, except that you are printing each value ($calhash{$key}) with a blank (see my $value = ""; at the top of your code), not each key and its associated value, as you clearly mean to do:
foreach my $key (sort {$b cmp $a} keys %calhash) { my $value = $calhash{$key}; print TESTFILE "$key;$value\n"; }
Update: Apologies to all and sundry who beat me to the punch here. When I started, there were no replies!
dmm
If you GIVE a man a fish you feed him for a dayIn reply to Re: Hash sorting
by dmmiller2k
in thread Hash sorting
by jamen
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |