Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Printing a hash in a specific order?

by Anonymous Monk
on Mar 15, 2003 at 15:55 UTC ( #243305=note: print w/replies, xml ) Need Help??

in reply to Printing a hash in a specific order?

What does this do?

my ($key) = keys %{$hashref};

Replies are listed 'Best First'.
Re: Re: Printing a hash in a specific order?
by Limbic~Region (Chancellor) on Mar 15, 2003 at 16:01 UTC
    Anonymous Monk,
    It is magic - bad magic, but magic none the less. Without showing you my very poorly written OO code. Basically, I am creating a complex hash (HoHo...). There is really only one key to the hash at any one time - which points further down the complex structure. So $hashref is a scalar that is a reference that points to the actual hash. The %{$hashref} is dereferencing the reference it to make it look like a real hash. The keys extracts the one and only key that is there. Putting the parens around the my ($key) part changes the context from scalar (which would have returned the number of keys i.e. 1) to a list context (which returns the one and only key).

    Cheers - L~R

      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

        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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://243305]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2018-05-27 14:02 GMT
Find Nodes?
    Voting Booth?