So, you basically have to print out a hash sorting lines using the value instead of the key, right? Keep in mind that using a hash won't allow you to keep the original relative order of the lines, but this does not affect what we're saying about the print.

If you had to sort only based upon the keys, you'd write something like this:

for my $k (sort keys %hash) { print "$k $hash{$k}\n"; }
Well, you're near. Remember that sort allows you to specify a bare block of code which is actually a sub that's called to establish the relative order of two elements $a and $b. So, you'd change the things a bit like this:
my @ordered_keys = sort { order($hash{$a}, $hash{$b}) } keys %hash; for my $k ( @ordered_keys ) { print "$k $hash{$k}\n" } sub order { my ($left, $right) = @_; # Perform comparison between $left and $right. Return # -1 if $left must come *before* $right, 0 if they are # equivalent, +1 if $left must come *after* $right }
You can include the code in order() directly in sort's block, of course, and use $a and $b instead of $left and $right, but do this only if readability doesn't suffer from this inclusion.

The actual implementation of the order() subroutine is left as exercise, but you could extract the last two characters from $left and $right, and use the cmp operator :)

Flavio
perl -ple'$_=reverse' <<<ti.xittelop@oivalf

Don't fool yourself.

In reply to Re: Crazy hash sorting issue. by polettix
in thread Crazy hash sorting issue. by rementis

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.