954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

lists and associate arrays

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";
}
Gaiety
Junior Poster
120 posts since Sep 2009
Reputation Points: 13
Solved Threads: 3
 

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 .

d5e5
Practically a Posting Shark
810 posts since Sep 2009
Reputation Points: 159
Solved Threads: 159
 

Thanks a lot.

Gaiety
Junior Poster
120 posts since Sep 2009
Reputation Points: 13
Solved Threads: 3
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You