http://www.perlmonks.org?node_id=243318


in reply to Re: Re: Printing a hash in a specific order?
in thread Printing a hash in a specific order?

Here's a more efficient idiom for grabbing a single key from a hash reference:

my $key = each %{$hashref};

The approach you're using with my($key) = keys %{$hashref}; essentially generates a list of the keys in memory, assigns the first element in the list to $key, and then throws rest of the list out. If the size of the hash is large this could be wasteful, but even with small hashes there is a noticeable difference between the two idioms when benchmarking.

Dan Kubb, Perl Programmer

Updated: Made minor corrections noted by Limbic-Region

Replies are listed 'Best First'.
Re: (dkubb) Re: (3) Printing a hash in a specific order?
by Limbic~Region (Chancellor) on Mar 15, 2003 at 16:57 UTC
    dkubb,
    Two minor corrections:

  • my $key = each %{$hashref}; - need to dereference the hash
  • my($key) = keys %{$hashref}; doesn't generate a list of keys in memory and assign the first one to key. It assigns all of them in serialized format to the variable. The reason why this works is because there is only one key.

    I also disagree with your analysis that your method would be faster in my example. Each has to retrieve both the key and lookup the value (which we are throwing away). My method is only retrieving a one element list of keys. I do appreciate the effort at making this more efficient. As I said - my first OO project and I know I am making a lot of mistakes. I think the proper way to fix this would be to start over.

    Cheers - L~R