alexxx has asked for the wisdom of the Perl Monks concerning the following question:

Greetings monks,
I need your help to keep in good shape my movie list!

I currently decided to keep it in an array of hashes:
push @recs, {id => $cid, director => $cdir, title => $ctit, type => $ctyp};

I wanted to output the records in a given order, i.e. not simply ordered by e.g.director, but with a sequence of preferred orderings, like (director,title,id,type), or (type,title,director,id), a possibility usually found in wordprocessors when dealing with tables.

any hint?
thanks!

alessandro

Replies are listed 'Best First'.
Re: sub-sorting a hash
by davorg (Chancellor) on Apr 26, 2006 at 15:24 UTC

    The FAQ How do I sort an array by (anything)? will probably help you.

    For example, to sort by title:

    @recs = sort { $a->{title} cmp $b->{title} } @recs;

    The FAQ shows how to sort by multiple values in your hashes.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: sub-sorting a hash
by rhesa (Vicar) on Apr 26, 2006 at 15:27 UTC
    use a custom sort block, like this:
    # sort by type, then director, then title @sorted { $a->{type} cmp $b->{type} || $a->{director} cmp $b->{director} || $a->{title} cmp $b->{title} } @recs;
Re: sub-sorting a hash
by Roy Johnson (Monsignor) on Apr 26, 2006 at 15:39 UTC
    I'd say to see Sort::Key, but I find it a little unclear. To roll your own, do something like this:
    my @sort_keys = qw(director title id type); use List::Util 'first'; sort { first {$a->{$_} cmp $b->{$_}} @sort_keys } @recs;

    Caution: Contents may have been coded under pressure.
      use Sort::Key::Multi 's4_keysort'; # s4 => 4 string keys @sorted = s4_keysort { @{$_}{qw(director title id type)} } @recs;