Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Re: Re: Back to Remedial Perl for Me: map{} function

by $code or die (Deacon)
on Dec 15, 2000 at 21:05 UTC ( [id://46856]=note: print w/replies, xml ) Need Help??


in reply to Re: Re: Back to Remedial Perl for Me: map{} function
in thread Back to Remedial Perl for Me: map{} function

Out of interest, why does this (both examples) print:
one => 1 three => 3 two => 2
and not:
one => 1 two => 2 three => 3

Replies are listed 'Best First'.
Re: Re: Re: Re: Back to Remedial Perl for Me: map{} function
by davorg (Chancellor) on Dec 15, 2000 at 21:07 UTC

    Because hashes are unordered.

    --
    <http://www.dave.org.uk>

    "Perl makes the fun jobs fun
    and the boring jobs bearable" - me

      "unsorted" would be more precise...the elements in the hash do have an order, but not not "in the order" that we might put them.
      That's what I thought, but it did the same order every time I ran it, so it seems that there is some order (i.e. it's not completely random). Was just wondering how perl decides to order it. Even Data::Dumping the hash gives the same order!
        The ordering of elements in a hash is based on the hash function. The hash function processes a key and determines where in the hash that key should be placed. For any given key, the hash function must always return the same result. A good hash function will tend to keep keys spread out in the hash; if all the keys end up in the same place in the hash, then you lose the benefit of having a hash.

        So, there is an "order" to the elements in the hash, but the order is not intended to be useful to the programmer, and keys may be reordered when the size of the hash changes.

        Oh, it is ordered in some way, just not any way that is obvious to the casual user. The sort order is indicative of how perl is modelling the hash internally. Yes you'll see the same order each time you run the script, but that may well not be true if you were to run it on another operating system or a different version of Perl.

        All in all, it's best to assume that the ordering is random.

        --
        <http://www.dave.org.uk>

        "Perl makes the fun jobs fun
        and the boring jobs bearable" - me

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://46856]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-03-28 16:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found