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

Hi,

I need to sort a list with a customized sort order, e.g. (a,c,d,e,b). This works fine as long I give the sortorder in the sort_sub like this:

@tobesorted=(b,a,d); @sorted=sort by_list @tobesorted; sub by_list{ @sortorder=(a,c,d,e,b); map { if ($a eq $sortorder[$_]){$ai=$_} } 0..$#sortorder; map { if ($b eq $sortorder[$_]){$bi=$_} } 0..$#sortorder; $ai <=> $bi; }

Nevertheless is there a possibility to hand over the list to the sub like:

@sorted=sort by_list(\@sortorder) @tobesorted; .... sub by_list{ @sortorder=@{$_[0]}; .....

I cant get the argument handed over to the sort_sub. Has that to do with the "local ($a,$b)" used for sort ? Any hints to write the code more elegant are appreciated.

Thanks, Hasenbraten

Replies are listed 'Best First'.
Re: give arguments to sort_sub
by Fletch (Bishop) on Apr 12, 2004 at 00:26 UTC
    @sorted = sort { by_list( \@sortorder ) } @tobesorted;

    Update: Or if you do it more than once with a few common orders:

    sub make_sorter { my $order = shift; return sub { by_list( $order ) }; } my $order1 = make_sorter( [ qw( a c d e b f ) ] ); my $order2 = make_sorter( [ qw( f b a d c e ) ] ); my @order1 = sort $order1, @tobesorted; my @order2 = sort $order2, @tobesorted; my @other2 = sort $order2, @othertobesorted;
•Re: give arguments to sort_sub
by merlyn (Sage) on Apr 12, 2004 at 00:31 UTC