in reply to sorting hash by a certain value (that it is in an array)

In complement to Corion's answer: Re: sorting hash by a certain value (that it is in an array)

Here is an example. You can use more complexe sorting method (see commented line: lc(...) cmp lc(...)) and optimized it with The Orcish Maneuver.
#!/usr/bin/env perl use strict; use warnings; my %books=( '34' => ['enlgish', 'dani M. rod', 54], '24' => ['spanish', 'ramk rovale', 41], '54' => ['enlgish', 'bob falicas', 17], ); my @sorted_books = sort { $books{$a}->[1] cmp $books{$b}->[1] #lc($books{$a}->[1]) cmp lc($books{$b}->[1]) } keys %books; print "@sorted_books";

Update: print sorted books

for my $book_id (@sorted_books) { print "$book_id: ",join ", ",@{ $books{$book_id} }; print "\n"; }

Replies are listed 'Best First'.
Re^2: sorting hash by a certain value (that it is in an array)
by gooyava (Novice) on Jul 17, 2012 at 13:27 UTC
    this is not about sorting an array, it's about sorting an hash that has arrays in it. the example by brx created a new sorted array @sorted_books. I need the %books hash to be sorted as so:
    %books=( '54' => ['enlgish', 'bob falicas', 17], '34' => ['enlgish', 'dani M. rod', 54], '24' => ['spanish', 'ramk rovale', 41], );
    I don't see how the example by brx gives me that. when I print out the %books hash using this:
    while (my($key, $value) = each(%books)){ print "$key: $value\n"; }
    I get the same unsorted result.

      A hash is a different data structure than an array. Its advantage is that it allows arbitrary strings as keys instead of just a number. The disadvantage is that it can't be sorted. Read about "hash tables" on wikipedia if you want to know why.

      Perhaps you could use Tie::IxHash?
      my %unordered=(...); tie my %ordered, "Tie::IxHash"; for my $key (sort {$unordered{$a}[1] cmp $unordered{$b}[1]} keys %$ +unordered) { $ordered{$key}=$unordered->{$key}; };