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

I have the below array of hashes which I'm creating using the File::Find method.

I would like to order the array by the key value file name so when I print the array out using the HTML Template method they are in a listed in a alphabetical order.

I've attempted various sort methods with interesting results.

Please can anyone help. I'm a newbie to perl so if i've made a school boy error forgive me.
$VAR1 = [ { 'file_name' => 'uk_campaign1_2005_06', 'details' => [ { 'value' => 'Harry Potter', 'name' => 'Owner' }, { 'value' => '24-11-2005', 'name' => 'Last Update' }, { 'value' => '13-12-2005', 'name' => 'End date' } ], 'file_dir' => 'Client01/uk_campaign1_2005_06' }, { 'file_name' => 'uk_campaign2_2005_08', 'details' => [ { 'value' => 'James Potter', 'name' => 'Owner' }, { 'value' => '25-11-2005', 'name' => 'Last Update' }, { 'value' => '13-01-2006', 'name' => 'End date' } ], 'file_dir' => 'Client01/uk_campaign2_2005_08' }, { 'file_name' => 'uk_campaign1_2005_05', 'file_dir' => '/Client01/uk_campaign1_2005_05' }, { 'file_name' => 'no_campaign1_2005_06', 'details' => [ { 'value' => 'Dobby', 'name' => 'Owner' }, { 'value' => '24-11-2005', 'name' => 'Last Update' }, { 'value' => '13-12-2005', 'name' => 'End date' } ], 'file_dir' => 'Client01/no_campaign1_2005_06' } ];

Replies are listed 'Best First'.
Re: Sorting an array of hashes
by friedo (Prior) on Dec 14, 2005 at 12:16 UTC
    You can use a custom sort block to do it. The block gets called for every sort iteration with the special variables $a and $b set to two of the items. In this case, they will be references to the various hashes in your array. You can then use the cmp operator to compare the file_name key alphabetically.

    my @sorted = sort { $a->{file_name} cmp $b->{file_name} } @files;