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

The output of the following to be print like :

apple boy cat

but it printing in different way

cat apple boy

Please find the following code

#!/usr/bin/perl use strict; use warnings; my %hash2=( a => "apple", b => "boy", c => "cat" ); my @keys=keys %hash2; foreach my $s (@keys) { print "$hash2{$s} "; }

Thanks.

Replies are listed 'Best First'.
Re: Printing Output in different way
by almut (Canon) on May 07, 2010 at 22:54 UTC

    Due to their inner workings, hashes don't return the entries in the order you entered them (or only by accident).  If the ordering matters, you can use the Tie::IxHash module.

    #!/usr/bin/perl use strict; use warnings; use Tie::IxHash; tie my %hash2, "Tie::IxHash"; %hash2=( a => "apple", b => "boy", c => "cat" ); my @keys=keys %hash2; foreach my $s (@keys) { print "$hash2{$s} "; } __END__ $ ./838968.pl apple boy cat
      Thanks. It works the same as defined in hash.
Re: Printing Output in different way
by Marshall (Canon) on May 07, 2010 at 23:07 UTC
    hash keys come in any order at all (not like an array where there is a fixed order). To print in alphabetic order you need to sort the keys.

    #!/usr/bin/perl use strict; use warnings; my %hash2=( c => "cat", a => "apple", b => "boy", ); my @keys= sort keys %hash2; foreach my $s (@keys) { print "$hash2{$s} "; } __END__ prints: apple boy cat
Re: Printing Output in different way
by toolic (Bishop) on May 08, 2010 at 01:19 UTC
Re: Printing Output in different way
by k_manimuthu (Monk) on May 08, 2010 at 04:32 UTC
    my %hash2=( a => "apple", b => "boy", c => "cat" ); print "\n$hash2{$_}" for (sort keys %hash2);

    while we use the sort function in hash. We access keys in asc order.

Re: Printing Output in different way
by rev_1318 (Chaplain) on May 08, 2010 at 14:14 UTC

    You do not state clearly what you want. Do you want the output:

    • in the order you entered them in the hash?
      then use Tie::IxHash, as suggested
    • in the order of the sorted keys?
      then use the sort keys solution
    • in the sorted order of the values and only the values?
      then sort values ĥash2 should suffice

    The mere statement The output of the following to be print like leaves things to be guessed...

    Paul