----- Original Message ----- 
From: "Luke Palmer" <[EMAIL PROTECTED]>
To: "Language List" <[EMAIL PROTECTED]>
Sent: Wednesday, February 11, 2004 10:11 PM
Subject: [perl] The Sort Problem


> I've been thinking about this problem which comes up in my code a lot:
>
>     @sorted = sort { $^a.foo('bar').compute <=> $^b.foo('bar').compute }
>                 @unsorted;
>
> Often the expressions on each side are even longer than that.  But one
> thing remains:  both sides are exactly the same, substitute a $^b for a
> $^a.
>
> I can see a couple less-than-desirable ways around this redundancy:
>
>     @sorted = sort { infix:<=>( *($^a, $^b)Â.foo('bar').compute ) }
>                 @unsorted;
>
> Which doesn't work if .compute returns a list... not to mention its
> horrible ugliness.  Another is to define a variant of sort (haven't had
> much practice with A6 material recently; here we go!):
>
>     multi sub sort (&block($) = { $_ } : [EMAIL PROTECTED]) {
>         sort { block($^a) cmp block($^b) } @data;
>     }
>
>     @sorted = sort { .foo('bar').compute } @unsorted;
>
> Which has the disadvantage of forcing you to use C<cmp> and forcing an
> ascending sort.
>
> Any other ideas?  Is a more general solution necessary?
>


   This is unrelated to the problem you mentioned, but there is another
annoying problem with sort as it is currently defined.  If you have an
@array and you want to replace it with the sorted version, you have to type
    @array = sort @array;

Besides being long-winded, this causes Perl to make an unnecessary copy of
the array.  It would be nice calling if sort (or reverse, or other similar
functions) in void context resulted in in-place modification of the array
that was input.

Joe Gottman


Reply via email to