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

The quick version:

Can I get the values of a hash in a given order without walking the hash?

The full story:

I have the results of a query in a hash via bound columns (a la http://www.perl.com/lpt/a/521)

I need to send some of those fields to a stored procedure on the db server in a particular order.

I have an array of the fields names I want (and in the correct order).

I know I can do something like this:

foreach $key (@field_names) { push @request, $results{$key} }
But is there a slicker, faster way?

Replies are listed 'Best First'.
Re: Order hash results
by ikegami (Patriarch) on Aug 24, 2009 at 16:25 UTC

    You can't fetch N items from the hash without having something that loops N times. That doesn't mean it has to be a foreach loop. It can be written more succinctly than what you posted by using a hash slice.

    What you posted is equivalent to

    push @request, @result{ @field_names };

    If the previous statement was my @request;, you can incorporate it as follows:

    my @request = @result{ @field_names };
Re: Order hash results
by Marshall (Canon) on Aug 24, 2009 at 18:28 UTC
    A hash table look-up is the fastest "complex" data structure on the planet, BUT you give up sequential access. Here you know the keys so that doesn't matter. If you do want N things, then you do N queries. I see no easier way. There is a syntax to get both the key and value at once, but "at the end of the day", it does N queries.

    If this func is going to be in a sub, then push onto a reference to array instead of returning @result from the sub(). That will be significantly faster.

Re: Order hash results
by ganeshk (Monk) on Aug 25, 2009 at 02:56 UTC
    Just in case you want the shorter form for the code you gave you can do..
    push @request, @results{@field_names}; # or you can replace the second parameter to push with # @results{qw(field1 field2 field3)}
    I am sorry if that's not what you want
Re: Order hash results
by NerfMan (Initiate) on Aug 25, 2009 at 14:28 UTC
    The hash splice will at least make it a bit easier to read.

    I think that's all I can ask for.