We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,931 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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";
}
2
Contributors
2
Replies
4 Days
Discussion Span
1 Year Ago
Last Updated
3
Views
Question
Answered
Gaiety
Junior Poster
135 posts since Sep 2009
Reputation Points: 13
Solved Threads: 3
Skill Endorsements: 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.

d5e5
Practically a Posting Shark
831 posts since Sep 2009
Reputation Points: 162
Solved Threads: 163
Skill Endorsements: 1
Question Answered as of 1 Year Ago by d5e5

Thanks a lot.

Gaiety
Junior Poster
135 posts since Sep 2009
Reputation Points: 13
Solved Threads: 3
Skill Endorsements: 0

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0815 seconds using 2.65MB