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

Hello, I have a requirement to sort elements in an array of hashes in perl and need your help for it. Given below is the code I have for it:

@List = (); $List[0]->{'time'} = "00:34:20"; $List[0]->{'date'} = "2011-09-13 00:34:20"; $List[0]->{'file'} = "abc.txt"; $List[0]->{'note'} = "dummy1"; $List[1]->{'time'} = "00:37:12"; $List[1]->{'date'} = "2011-09-13 00:37:12"; $List[1]->{'file'} = "abc1.txt"; $List[1]->{'note'} = "dummy2"; $List[2]->{'time'} = "00:33:00"; $List[2]->{'date'} = "2011-09-13 00:33:00"; $List[2]->{'file'} = "abc2.txt"; $List[2]->{'note'} = "dummy3"; my @sorted = sort { $a->{'date'} <=> $b->{'date'} } @List;

I need to sort the hashes by 'date' so when the array is printed, the files are listed by creation time, with the most recent being the first. But the entries do not get sorted. Any idea how to sort the hash entries in the array? Thanks!

Replies are listed 'Best First'.
Re: Sorting an array of hashes
by Corion (Patriarch) on Sep 22, 2011 at 07:14 UTC

    Read perlop. The <=> operator is the operator for comparing numbers. Use the cmp operator for comparing strings.

Re: Sorting an array of hashes
by Kc12349 (Monk) on Sep 22, 2011 at 17:58 UTC

    As a peripheral note, there are several modules which allow you to keep ordered hash keys. I'm not sure if it applicable to your case, but should you want to be able to refer to entries in your data set by name and maintain order as you would in an array, this is possible with some additional overhead.

    My personal choice is Tie::Hash::Indexed, as it is XS based and fast, though there are many other similar choices using tie.

    If you sort entries into the hash before as you add them, keys will then continue to return this sorted order back to you.

      Thanks for all the suggestions! Using 'cmp' in lieu of '<=>' indeed solve my problem.

Re: Sorting an array of hashes
by Anonymous Monk on Sep 22, 2011 at 15:26 UTC
    Since your data has equal length fields (all the numeric bits padded with leading zeroes) AND the fields are in decreasing order of precedence, the ASCII-betical sort provided by cmp will work fine here.

    -Greg

Re: Sorting an array of hashes
by petdance (Parson) on Sep 22, 2011 at 14:50 UTC
    You can't sort a hash. You can print a hash in sorted order.

    xoxo,
    Andy