Chankey Pathak
Chankey Pathak

Reputation: 21676

In what order the keys/values are getting assigned?

my %fruit_colors = ("apple", "red", "banana", "yellow");
my @fruits = keys %fruit_colors;
my @colors = values %fruit_colors;
print @fruits;            #output is: bananaapple
print "\n";
print @colors;            #output is: yellowred

Codepad link: http://codepad.org/I0wrTPSe

Could anyone explain me why is the output of print @fruits; is bananaapple. I thought it would be applebanana. I think the keys of the hash %fruit_colors are getting assigned to the array @fruits in the reverse order i.e. last element is getting assigned first. Is it?

Same case with the print @colors; Why yellowred instead of redyellow?

Upvotes: 2

Views: 137

Answers (3)

Tudor Constantin
Tudor Constantin

Reputation: 26861

Roger is right when saying that no order can be assumend while working with Perl hashes.

Besides that, is recommended to use fat commas when working with hashes, so your initial assignment should look like:

my %fruit_colors = ("apple" => "red", "banana" => "yellow");

Imagine having a hash with 20 key/value pairs - how will you know at pair 14 which is the key and which is the value?

Upvotes: 3

Sinan Ünür
Sinan Ünür

Reputation: 118156

See perldoc -f keys. perldoc comes with Perl. When learning the language, it is useful to have at least read something about the language in the first place:

The keys of a hash are returned in an apparently random order. The actual random order is subject to change in future versions of Perl, but it is guaranteed to be the same order as either the values or each function produces (given that the hash has not been modified). Since Perl 5.8.1 the ordering can be different even between different runs of Perl for security reasons (see Algorithmic Complexity Attacks in perlsec).

Upvotes: 7

Roger
Roger

Reputation: 15813

The order is non-deterministic and depends on the underlying implementation of the hash algorithm which could be subject to change. You should never rely on the ordering and you should add your own sort in if you need sorted results.

See the perl documentation here

Upvotes: 10

Related Questions