Hi Balachandran,

On Wednesday 06 Apr 2011 16:22:44 Balachandran Sivakumar wrote:
> Hi,
> 
>          I am trying to learn hashes in perl. I created an hash
> variable with 4 keys. I tried printing the keys in the hash by:(hash
> variable is %machines)
> 
> foreach $key (keys %machines) {
>      print "$key\n";
> }
> 
> I noticed that the order in which the keys are printed is different
> from the order in which I stored them. Is that expected ? If so, what
> determines the order.

The order is determined by perl 5's internal hashing implementation and cannot 
be relied on. If you want a particular order use an array, sort the keys first 
or use a CPAN module. For more information see the resources on:

http://perl-begin.org/topics/hashes/

What you can rely on is for the order of the keys in the hash to remain the 
same as long as it is not modified and this is the order in keys(), values() 
and each().

> 
> Another question is that, when I tried something like:
> 
> my @my_machines = %machines;
> print "@my_machines\n";
> 
> I noticed that the output is exactly the reverse of the order in which
> I had stored them in the hash. Is this also the expected behaviour ?
> If so what is the reason behind that ?
> 
> Can someone please help me with these 2 newbie questions ?
> 
> 
> PS: I am used to program. So, if I am doing something that is not the
> perl way of doing it, please do let me know. Thanks

Also see:

http://www.nntp.perl.org/group/perl.beginners/2011/03/msg116305.html

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Apple Inc. is Evil - http://www.shlomifish.org/open-source/anti/apple/

I invented the term Object-Oriented, and I can tell you I did not have C++ in
mind.                  -- Alan Kay (Attributed)

Please reply to list if it's a mailing list post - http://shlom.in/reply .

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to