in reply to Sorting an array based on hash values

my @sorted = sort {$order{$a} <=> $order{$b}} @to_be_ordered;

This is not well-behaved for elements of @to_be_ordered that aren't present in %order.

--
The hell with paco, vote for Erudil!
:wq

Replies are listed 'Best First'.
Re: (FoxUni) Re: Sorting an array based on hash values
by thelenm (Vicar) on Jun 20, 2002 at 17:35 UTC
    If you want values in @to_be_ordered that are not in %order to be put at the end of the list, you might try something like this:
    my @sorted = ((sort {$order{$a} <=> $order{$b}} grep {exists $order{$_}} @to_be_ordered), grep {not exists $order{$_}} @to_be_ordered);
    Of course, this runs through @to_be_ordered twice, which is inefficient. So you might use two temporary arrays:
    my (@exists, @not_exists); push @{exists $order{$_} ? \@exists : \@not_exists }, $_ for @to_be_or +dered; my @sorted = ((sort {$order{$a} <=> $order{$b}} @exists), @not_exists) +;

    -- Mike

    --
    just,my${.02}