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

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

When I run this script why do I get the keys and values not in order?
Thank you,
#!/usr/bin/perl use strict; use warnings; my%hash1 = ("a",1,"b",2,"c",3,"d",4); while (my@values = each(%hash1)){ print "The key/value pair is @values \n"; }

C:\JPARK\JPERL>test.pl
The key/value pair is c 3
The key/value pair is a 1
The key/value pair is b 2
The key/value pair is d 4

Replies are listed 'Best First'.
Re: Not in order in Hash output
by toolic (Bishop) on Oct 10, 2012 at 19:49 UTC
    perlintro
    Hashes have no particular internal order, though you can sort the keys and loop through them.

    See also:

Re: Not in order in Hash output
by aitap (Curate) on Oct 10, 2012 at 19:51 UTC
    perldoc perldata:
    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.
    Sorry if my advice was wrong.
Re: Not in order in Hash output
by ikegami (Patriarch) on Oct 10, 2012 at 22:30 UTC
    Just like arrays, hash return their elements in the order they are physically arranged in the hash. Hashes differ from arrays in that one cannot control the order in which elements are arranged, and the order can change whenever the number of hash element changes.

      Try this,

      use strict; use warnings; use Tie::IxHash; my %hash1 = (); tie %hash1, "Tie::IxHash"; %hash1 = ("a",1,"b",2,"c",3,"d",4); while (my@values = each(%hash1)){ print "The key/value pair is @values \n"; }
Re: Not in order in Hash output
by MidLifeXis (Monsignor) on Oct 11, 2012 at 12:37 UTC

    Just a couple comments on the coding style I have seen you use in many of your posts.

    • my is a token separate from the name of the variable. Whitespace can help with readability. The formatting that you seem to prefer (my$var ...) is not one that I typically see, is unexpected, and (at least for me) causes a break in the flow while mentally parsing the code. More typical is my $var ....
    • When assigning to a hash, it can be more readable to write %hash = ( a => 1, b => 2, c => 3, ... ). The 'fat comma' is another indicator to my synaptic-based parser that this is a hash assignment.

    Nothing that is end-of-the-world type stuff, but more indicators to help my future-self understand what I was thinking when I originally wrote the code.

    --MidLifeXis

Re: Not in order in Hash output
by johngg (Canon) on Oct 10, 2012 at 20:19 UTC