I still can't get it to sort by values. Sorting by keys seems to be easy, but it looks like values were not meant to be sorted by.

No, absolutely not. Sorting by values is OK, as shown by examples above. If you don't get it right, then it means you are simply not doing right.

This is an example built on the code proposed by Kenosis. I have changed and added a couple of names to make sure that the states don't get in the right order just by chance (which was the case with the original data you gave):

use strict; use warnings; use Data::Dumper; my @fname = ( "Philip", "John", "Daniel", "John", "Ted" ); my @lname = ( "Johnson", "Hill", "Sharp", "Evans", "McCain" ); my @state = ( "AK", "CA", "AL", "WI", "TX"); my %hash = map { $fname[$_] . ' ' . $lname[$_] => $state[$_] } 0 .. $# +state; print "Unsorted:\n" ,Dumper \%hash; print "==========\n"; print "Sorted:\n", map "$_, $hash{$_}\n", sort {$hash{$a} cmp $hash{$b +}} keys %hash;
which gives the following output:
$ perl sort_hash.pl Unsorted: $VAR1 = { 'John Evans' => 'WI', 'Philip Johnson' => 'AK', 'John Hill' => 'CA', 'Ted McCain' => 'TX', 'Daniel Sharp' => 'AL' }; ========== Sorted: Philip Johnson, AK Daniel Sharp, AL John Hill, CA Ted McCain, TX John Evans, WI
As you can see, the data is now sorted by the values (i.e. the State).

If you still don't succeed to do it, please show your code.


In reply to Re^5: Creating a hash from arrays by Laurent_R
in thread Creating a hash from arrays by cspctec

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.