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

Greetings esteemed holy men of Perl, I use the following hash in my code :
%fetch= sse_date => 4934056723, bld_num= 7.3.998.0.0, sse_date => 4934099999, bld_num= 7.3.1003.0.0, sse_date => 4949999999, bld_num= 7.3.1089.0.0, . . . etc. etc.
What I want to do is to sort all of the values in key sse_date from highest to lowest, and then grab the top 5 associated values of key bld_num, storing those values in an array.
How do I do this ?
I've attempted this via the sort function along with $b <=> $a criterion, but I can't get it to work ... Please help ...

Thanks in advance, Travis Weir

Replies are listed 'Best First'.
Re: Sorting hash values
by Errto (Vicar) on Jan 07, 2005 at 21:23 UTC
    You can't create a hash like
    %fetch= (sse_date => 4934056723, bld_num => 7.3.998.0.0, sse_date => 4934099999, bld_num => 7.3.1003.0.0, sse_date => 4949999999, bld_num => 7.3.1089.0.0);
    because each key (such as "sse_date") can only appear once in a given hash. So that code will simply produce a hash with two keys and effectively one row of data. Rather I assume you mean that you want to have an array of hashes, something like
    my @fetch = ({sse_date => 4934056723, bld_num => '7.3.998.0.0'}, {sse_date => 4934099999, bld_num => '7.3.1003.0.0'}, ... );
    In that case you would see something like
    my @sorted = map { $_->{bld_num} } sort { $a->{sse_date} <=> $b->{sse_ +date} } @fetch;
    and go from there.
Re: Sorting hash values
by Zaxo (Archbishop) on Jan 07, 2005 at 21:31 UTC

    I'd like to see what Data::Dumper says is in your hash. What you have written has typos or is plain wrong. Just adding parentheses around the data yields a hash with only two keys. Do you mean to have an AoH? If so, enclose the sets of distinct data in curlies to get a hash ref in each slot and make the named structure an array. That will make the most sense for sorting, too.

    Here's what I think you wanted,

    my @fetch = ( { sse_date => 4934056723, bld_num => '7.3.998.0.0' }, { sse_date => 4934099999, bld_num => '7.3.1003.0.0' }, { sse_date => 4949999999, bld_num => '7.3.1089.0.0' }, # . . . etc. etc. ); my @sorted_fetch = sort { $b->{'sse_date'} <=> $a->{'sse_date') } @fetch;
    Your bld_num fields were in danger of becoming deprecated v-strings, so I quoted them.

    After Compline,
    Zaxo

Re: Sorting hash values
by sgifford (Prior) on Jan 07, 2005 at 21:28 UTC
    That doesn't look like a hash; if you coded it as you have above, you'd end up with only one entry for sse_date and one for bld_num. Do you actually have a list of hashes, or a hash of lists, or?...Can you show us a small snippet of the code where you create this?