Search code examples
perlperl-data-structures

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.


Solution

  • 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;