Labels

Wednesday, October 30, 2013

Perl sort function

Sort in alphabetical order, using 'cmp'; sort in numerical order, using '<=>'.

Sort an array:

    my @new =  sort {$a cmp $b} @old;

Sort a hash (sort by key, return sorted keys):

    my @new =  sort {$a cmp $b} keys %old;

Sort a hash (sort by value, return sorted keys):

    my @new =  sort {$old{$a} cmp $old{$b}} keys %old;

No comments:

Post a Comment