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

Hi Monks! I have a question on sorting. Say I have the following
@elements = ("hohoho" , "work" , "gates" , "ragarnok" , ".");
i want to sort the list in the elements from the longest string length to the smallest length. is there any fast/smart way of doing it? I been converting this data into a hash and created a key based on length of the elements and sorting that ie $HASH{"6"}{"hohoho"} = 1;

20040904 Edit by castaway: Changed title from 'Sort Question'

Replies are listed 'Best First'.
Re: Sort by string length
by kesterkester (Hermit) on Sep 03, 2004 at 21:59 UTC
    You can give the sort function a custom sorting subroutine, using the special variables $a and $b. E.g.:

    @sorted = sort { length $a <=> length $b } @elements

    See also perldoc -q sort

      wow......that just blew my mind!
Re: Sort by string length
by Enlil (Parson) on Sep 03, 2004 at 21:59 UTC
    my @sorted_by_length = sort { length($a) <=> length($b) } @elements;
    or if you feel so inclined to do a schwartzian type transform (used when an expensive function is used to evaluate order):
    my @sorted_by_length = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, length($_) ] } @elements
    HTH

    -enlil

Re: Sort by string length
by bobf (Monsignor) on Sep 03, 2004 at 22:03 UTC
Re: Sort by string length
by Anonymous Monk on Sep 03, 2004 at 23:38 UTC
    If your array is small, it doesn't matter how you sort. For large arrays, a GRT is fastest. For instance:
    @elements = @elements [map +(unpack $format, $_) [-1], sort map pack ( +$format, length $elements [$_], $_), 0 .. $#elements];
    And a GRT is far less memory hungry than an ST.