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

Hi Brethren,
Is there a way to keep the "keys" in the same order from a hash when passed to an array

my @sorted_scores =  keys %hashFinal;

So they can be used to map in the following again retaining the same order

my @sorted_line_nums = map { $Reversevalues{$_} } @sorted_scores;

Many thanks

Gavin
It was suggested that I use Tie::Ix Hash but there seem to be many different versions.
Can someone suggest a version to tie both Hash and Array or is it necessary to install more than one module?

Replies are listed 'Best First'.
Re: Keeping "keys" in order when passed to an Array
by gaal (Parson) on Apr 09, 2006 at 12:19 UTC
Re: Keeping "keys" in order when passed to an Array
by QM (Parson) on Apr 09, 2006 at 13:56 UTC
    [Aside: It seems that not using newlines inside <code> tags prevents the [download] link from appearing. In the future, some of your posts may benefit from the [download] link.]

    Ordinarily, sort would be used:

    my @sorted_scores = sort keys %hashFinal; my @sorted_line_nums = map { $Reversevalues{$_} } @sorted_scores;
    Your question seems odd to me, because if this is representative code, then @sorted_scores and @sorted_line_nums will have corresponding values. There are no situations I've come across that need the internal hash "order" to be preserved. Since the internal hash order is data dependent, version dependent, (and possibly platform dependent,) I've always used sort when I need order.

    I can imagine some situations where you want the insert order, yet still need to use the associative lookup capability of a hash. In that case, gaal's suggestion of Tie::IxHash seems right on. Any other order implies an ability to discriminate a correctly ordered list and an incorrectly ordered list, and again sort is recommended.

    Perhaps you've just overlooked that sort can take a user supplied sort subroutine?

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

Re: Keeping "keys" in order when passed to an Array
by McDarren (Abbot) on Apr 09, 2006 at 13:30 UTC
    You could sort the keys when you pass them to @sorted_scores, like so:
    my @sorted_scores = sort keys %hashFinal;
    Then as long as:
    • You don't add or remove any keys, and
    • You sort them again when you map them
    ..then (I believe) you should be okay.

    However, that's still pretty fragile and probably not really recommended.

    Cheers,
    Darren :)