Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!wuarchive!uunet!convex!usenet From: tchrist@convex.COM (Tom Christiansen) Newsgroups: comp.lang.perl Subject: Re: printing assoc array in non-alphabetical order Message-ID: <1991May08.183237.6522@convex.com> Date: 8 May 91 18:32:37 GMT References: <46485@bcsaic.UUCP> Sender: usenet@convex.com (news access account) Reply-To: tchrist@convex.COM (Tom Christiansen) Organization: CONVEX Software Development, Richardson, TX Lines: 69 Nntp-Posting-Host: pixel.convex.com From the keyboard of vince@bcsaic.UUCP (Vince Skahan): :[...sigh...hope the previous Cancels on this took effect : and you only got one...] : :I have an associative array sorting question (I think)... :but it might be more related to keys. : :The question is "how can I get an associative : array to print in a specified (by me) order that : is NOT either alphabetic or reversed-alphabetic ?" : :The following fragment prints: : net.apr : net.feb : net.jan : net.mar : :when I want : net.jan : net.feb : net.mar : net.apr : :how can I get what I'm looking for in the following :example ??? : :--------------------- example ------------------- :%files=("net.jan",1,"net.feb",2,"net.mar",3,"net.apr",4); :foreach $item (sort keys %files) :{ : print "$item\n"; :} :------------------------------------------------- You need to declare a subroutine to do the sorting for you. This is similar to what you do with qsort(3), if you're familiar with that. In this case, it's pretty easy, because you already have an array whose values are the sorting order. Given your example, all you need to do is this: for $item (sort byval keys %files) { print "$item\n"; } sub byval { $files{$a} <=> $files{$b}; } Somewhat more generally, you may want an array like this: @month{'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'} = 1..12; and a sort routine like this: sub bymonth { local($m1) = $a =~ /\.\w{3}/; local($m2) = $b =~ /\.\w{3}/; $month{$m1} <=> $month{$m2}; } For large data sets you wouldn't really want to do the regexp each time. --tom -- Tom Christiansen tchrist@convex.com convex!tchrist "So much mail, so little time."