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

Hi, I hope this is not too trivial. I have a hash that is filled and then passed into another function. The problem is this function needs the order of the hash keys in a specific way. Anybody know how to do this

eg My hash gets filled so it looks like
%my_hash =('cat' =>,7, 'dog'=>3, 'cow'=>9,)
but needs to be in this order for use in a function
%my_hash = ('dog' => 3, 'cat' => 7, 'cow' => 9,)
basically I need to sort the hash by the specific order of this array
@array= ("dog","cat","cow")
then I can use tie:IxHash to preserve the order

Many thanks for any help.

Replies are listed 'Best First'.
Re: hash ordered by an array
by BrowserUk (Patriarch) on Jul 11, 2008 at 09:56 UTC

    In general, it doesn't make sense to want a hash in a particular order.

    Put another way, if you need things in a particular order, a hash is usually the wrong data structure. You can do it, as testimonied by the many modules that will do it for you, but if you explain why you think you need this, you will often get a better solution.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      i agree completely, if you would like to have particulary orderd structure of data it is better to use @arrays they have indexes that sorts your data in particular way , %hashes are special for their keys that are associated with some value. i mean, you could sort those keys like this:
      sort keys %hash;
      but to do it in a particular order you would somehow have to index those keys. top of the head solution;
      %hash = ('dog' => 1, 'big' => 5, 'jak' => 4, 'mack' => 19); @array = qw(dog mack jak big); foreach $val (@array){ print "$hash{$val}\n"; }
      in this way you are doing, in a particular order something with your %hash values. i suppose this isn't exactly what you had in mind but...
Re: hash ordered by an array
by Anonymous Monk on Jul 11, 2008 at 07:04 UTC
    use Tie::IxHash; tie %order, 'Tie::IxHash', map { $_ => $my_hash{$_}; } @array;
Re: hash ordered by an array
by Narveson (Chaplain) on Jul 11, 2008 at 17:11 UTC

    Just a guess - do you need the values in a particular order? That's easy with a hash slice.

    my %hash = ( cat => 7, dog => 3, cow => 9, ); my @array = ("dog","cat","cow"); my @ordered_values = @hash{@array}; # (3, 7, 9)
      Thanks, Thats exactly what I needed!