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 day
But,
TEACH him to fish and you feed him for a lifetime

In reply to Re: Hash sorting by dmmiller2k
in thread Hash sorting by jamen

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.