Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!think.com!zaphod.mps.ohio-state.edu!wuarchive!uwm.edu!linac!convex!usenet From: tchrist@convex.COM (Tom Christiansen) Newsgroups: comp.lang.perl Subject: Re: assoc array Keywords: assoc array, keys, order Message-ID: <1991May18.160757.15011@convex.com> Date: 18 May 91 16:07:57 GMT References: <5102@syma.sussex.ac.uk> Sender: usenet@convex.com (news access account) Reply-To: tchrist@convex.COM (Tom Christiansen) Organization: CONVEX Software Development, Richardson, TX Lines: 54 Nntp-Posting-Host: pixel.convex.com From the keyboard of sylvank@syma.sussex.ac.uk (Sylvan Katz): :I have an application which requires that I initialize an associative :array for counting purposes: : :EG: : : %matrix = ('A',0,'AA',0,'B',0,'BB',0); : :However, when I examine the order of the array elements with : : foreach $key (keys %matrix) { print "$key ";} : :I find order is : : BB A B AA : :Any suggestions on how I can PRESERVE the initial order (it is :imperative for my applications) ? If you're not adding any elements to the array, you could do this: @keys = ('A','AA','B','BB'); @matrix{@keys} = (); or, if having the values initialized to undef bothers you: @matrix{@keys} = (0) x @keys; Then process them with: for $key (@keys) { print "key ", $key, " is ", $matrix{$key}, "\n"; } Other more baroque ideas come to mind, like this one, which might perhaps be of use to you if you have some other criteria I'm not aware of: %order = (); $order = 0; for (@keys) { $order{$_} = $order++; } # later on... sub by_order { $order{$a} <=> $order{$b}; } for (sort by_order keys %matrix) { print "key ", $key, " is ", $matrix{$key}, "\n"; } In short, it all else fails, call an auxiliary function to help you get the ordering down. --tom -- Tom Christiansen tchrist@convex.com convex!tchrist "So much mail, so little time."