Chinmoy
Chinmoy

Reputation: 503

Unable to understand the behaviour of Perl hash ordering

I am a beginner in Perl and I am trying to run this sample example from "Beginning Perl:Curtis Poe"

#!/perl/bin/perl

use strict;
use warnings;
use diagnostics;

my $hero = 'Ovid';
my $fool = $hero;
print "$hero isn't that much of a hero. $fool is a fool.\n";

$hero = 'anybody else';
print "$hero is probably more of a hero than $fool.\n";

my %snacks = (
    stinky   => 'limburger',
    yummy    => 'brie',
    surprise => 'soap slices',
);
my @cheese_tray = values %snacks;
print "Our cheese tray will have: ";
for my $cheese (@cheese_tray) {
    print "'$cheese' ";
}
print "\n";

Output of the above code, when I tried on my windows7 system with ActivePerl and in codepad.org

Ovid isn't that much of a hero. Ovid is a fool. 
anybody else is probably more of a hero than Ovid.
Our cheese tray will have: 'limburger''soap slices''brie'

I am not clear with third line which prints 'limburger''soap slices''brie' but hash order is having 'limburger''brie''soap slices'.

Please help me to understand.

Upvotes: 1

Views: 93

Answers (3)

jsta
jsta

Reputation: 3403

I think the key is:

my @cheese_tray = values %snacks

From [1]: http://perldoc.perl.org/functions/values.html "Hash entries are returned in an apparently random order. The actual random order is specific to a given hash; the exact same series of operations on two hashes may result in a different order for each hash."

Upvotes: 1

toolic
toolic

Reputation: 62227

perldoc perldata:

Hashes are unordered collections of scalar values indexed by their associated string key.

You can sort keys or values as needed.

Upvotes: 6

TLP
TLP

Reputation: 67910

Hashes are not ordered. If you want a specific order, you need to use an array.

For example:

my @desc = qw(stinky yummy surprise);
my @type = ("limburger", "brie", "soap slices");
my %snacks;
@snacks{@desc} = @type;

Now you have the types in @type.

You can of course also use sort:

my @type = sort keys %snacks;

Upvotes: 6

Related Questions