KEY2 is a single key with a single value, so you can't sort that. Maybe you mean "by the second key"? But you don't say if you want to sort the keys or the values. OK, since you said KEY2 then I'll guess you want to sort the keys.

I added some data items to your hash, I don't know your data format, but I hope you get the idea. You might try this:
use strict; use warnings; my $hash; $hash->{"AAA"}->{"KEY1"} = "VALUE1"; $hash->{"AAA"}->{"KEY2"} = "VALUE2"; $hash->{"AAA"}->{"KEY3"} = "VALUE3"; $hash->{"AAA"}->{"KEY9"} = "VALUE3"; $hash->{"AAA"}->{"KEY10"} = "VALUE3"; $hash->{"AAA"}->{"KEY123"} = "VALUE3"; $hash->{"AAA"}->{"KAY1"} = "VALUE1"; $hash->{"AAA"}->{"KAY2"} = "VALUE2"; $hash->{"AAA"}->{"KAY3"} = "VALUE3"; my @result = sort keys %{$hash->{"AAA"}}; print "@result\n";
But that just gives:
KAY1 KAY2 KAY3 KEY1 KEY10 KEY123 KEY2 KEY3 KEY9
because the default sort is textual. We want a numeric sort on the second part of the key (I'm guessing here on your data format) so we need a bit more work:
sub keycmp { $a =~ /^(\D*)(\d*)$/; my $a_txt = $1; my $a_num = $2; $b =~ /^(\D*)(\d*)$/; my $b_txt = $1; my $b_num = $2; if ($a_txt eq $b_txt) { return $a_num <=> $b_num } else { return $a_txt cmp $b_txt } } @result = sort keycmp keys %{$hash->{"AAA"}}; print "@result\n";
Gives:
KAY1 KAY2 KAY3 KEY1 KEY2 KEY3 KEY9 KEY10 KEY123

In reply to Re: Sorting a multidimensional hash by column by cdarke
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.