Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: each() function used in associative arrays gives incorrect unordered output.

by Juerd (Abbot)
on Jan 19, 2002 at 20:03 UTC ( [id://140081]=note: print w/replies, xml ) Need Help??


in reply to each() function used in associative arrays gives incorrect unordered output.

Hashes aren't stored in the order they were defined. They're stored in whatever order perl thinks is efficient. If you had read ANY documentation on hashes, you would know that. Yes, each() gives unordered output (actually, it is ordered in a way, but the order is a bit hard to predict), but that's not incorrect. Your assumption that perl always DWYM is incorrect.

(Update (200201191751+0100) Removed offensive text.
Here's a list of documents that would have helped you out:
  • perldoc -q order gives exactly one hit, from perlman:perlfaq4:
    How can I make my hash remember the order I put elements into it?
    Use the Tie::IxHash from CPAN.
  • perldata is the place to look for information about data types. A quick search for the word "order" here gives the following paragraph:
    Note that just because a hash is initialized in that order doesn't mean that it comes out in that order. See "sort" in perlfunc for examples of how to arrange for an output ordering.
  • You used each, so I'll look up that documentation as well (in perlfunc):
    Entries are returned in an apparently random order. The actual random order is subject to change in future versions of perl, but it is guaranteed to be in the same order as either the "keys" or "values" function would produce on the same (unmodified) hash.
    Perlfunc has similar warnings in the keys and values department :)
As you can see, there's plenty of documentation on this subject. You just didn't read it. Next time, please RTFriendlyM before asking a question that has already been answered in great detail.

BTW, you said "... in the order as it is in the array", but didn't use any array. (The thing right of the = in your hash assignment is called a list - an array is mutable, a list is not.)

2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-03-29 00:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found