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

Random Value Generation in an Hash

by vishi83 (Pilgrim)
on Oct 20, 2005 at 07:18 UTC ( #501555=perlquestion: print w/replies, xml ) Need Help??
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 (Vicar) 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.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://501555]
Approved by gube
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2018-06-24 00:44 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.