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

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

Please see this code below...
#!/usr/bin/perl package Simple; use Class::MethodMaker get_set => [qw(Name Id Team)], new_hash_init => 'hash_init'; sub init { my $self = shift; return $self->hash_init(%values); } 1; use strict; use warnings; use Simple; use Data::Dumper; my $test; line : x $test=Simple->hash_init(Name=>'Vishi', Id=>1049,Team=>'OpenS +ource'); print Dumper $test;

In my line : X ... when i pass an hash to my hash_init method and print it ($test), i find my arguments getting printed randomly, even in this Obj Oriented Style .. I want them to get printed as
Name=>'vishi', Id=>1049,Team=>'OpenSource' But these values are not in order..

Thanks in advance.. vishi

Replies are listed 'Best First'.
Re: Random Value Generation in an Hash
by virtualsue (Vicar) on Oct 20, 2005 at 08:35 UTC
    Hashes by design do not store or present their key/value pairs in the order in which they have been inserted. This is documented in perldoc perldata.

    See Tie::IxHash for one way to preserve the order in which keys have been added to a hash.

Re: Random Value Generation in an Hash
by Skeeve (Parson) on Oct 20, 2005 at 07:53 UTC

    If you want a specific order in your output, you have to take care for it.

    It's the implementation of hashes that "randomizes" the order of elements.


    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e