Another variation for sorting a multi dimensional hash.

#!/usr/bin/perl # Sorting a multi dimensional hash example. my %user, $uname, $i, $score; my @List = qw(Charlie Madi Becky Paul); foreach $uname (@List) { $user{$uname}{'user'}=$uname; $user{$uname}{'score'}=int(rand(800))+100; } # unsorted print "- unsorted -\n\n"; foreach $i (keys %user) { print "$user{$i}{'user'}\t$user{$i}{'score'}\n"; } # Sort ascending on score dimension print "\n\n - Sort on score dimension ascending -\n\n"; foreach $i ( sort { $user{$a}{'score'} <=> $user{$b}{'score'} } keys % +user) { print "$user{$i}{'user'}\t$user{$i}{'score'}\n"; } # Sort descending on score dimension print "\n\n - Sort on score dimension descending -\n\n"; foreach $i ( sort { $user{$b}{'score'} <=> $user{$a}{'score'} } keys % +user) { print "$user{$i}{'user'}\t$user{$i}{'score'}\n"; } exit 0;


Sample output
# perl hsort2d.pl
- unsorted -

Paul      684
Becky   162
Charlie  694
Madi     805

- Sort on score dimension ascending -

Becky   162
Paul      684
Charlie  694
Madi     805

- Sort on score dimension descending -

Madi     805
Charlie  694
Paul      684
Becky   162

#


In reply to Re: Sorting a multidimensional hash by column by dcronin135
in thread Sorting a multidimensional hash by column by piccard

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.