Hi,
I have just started learning PERL.

below is the code i have written , i am expecting the same order that of array when i print the contents.
but the output was

29
25
Michael
29
Walter
34
Donny
25
Sobzchak
30

can some body please clarify the behaviour of arrays/foreach.

%ages = ("Sobzchak",30,
          "Michael", 29,
          "Walter",34,
           "Donny",25,
          );

print $ages{"Michael"}."\n";
print $ages{"Donny"}."\n";

@info = %ages;

foreach $item ( @info ) {
        print $item."\n";
}

Recommended Answers

All 2 Replies

An associative array, otherwise known in Perl as a hash, does not preserve the order in which the elements were added. If you want to list the contents of a hash in a particular order you can sort the keys according to rules which give you the desired result. If you want to sort by keys, or values, in ascending or descending order, by numeric or alphabetic comparisons, etc. you can do that. But 'the same order' in which elements were added to a hash cannot be determined. See Perl Tutorial - Hashes.

If you need to save key-value pairs in a particular sequence you could build a more complex data structure, such as an array of references to hashes. See Arrays of Hashes.

Thanks a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.