1.11M Members

lists and associate arrays

 
0
 

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";
}
 
0
 

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.

Question Answered as of 2 Years Ago by d5e5
 
0
 

Thanks a lot.

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article