Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!crdgw1!uunet!convex!newsadm From: tchrist@convex.COM (Tom Christiansen) Newsgroups: comp.lang.perl Subject: Re: Sortin based on part of an associative array? Message-ID: <1991Apr16.112826.10352@convex.com> Date: 16 Apr 91 11:28:26 GMT References: <17524@venera.isi.edu> <8310026@hpnmdla.hp.com> Sender: newsadm@convex.com (news access account) Reply-To: tchrist@convex.COM (Tom Christiansen) Organization: CONVEX Software Development, Richardson, TX Lines: 32 Nntp-Posting-Host: pixel.convex.com From the keyboard of chrise@hpnmdla.hp.com (Chris Eich): [quoting some faulty code of mine, deleted here] :This doesn't seem to work; sort_by_len returns the lengths, not the keys :of the original table. : :You seem to want sort_by_field to return the keys of the original table, :so how about this: : : sub sort_by_field { : local(*Table, $Field) = @_; : local(%Keys); : : foreach (keys %Table) { : $Keys{(split(/:/, $Table{$_}))[$Field]} = $_; : } : @Table{@Keys{sort by_num keys %Keys}}; : } After staring at it until it comes into focus, yes, this is much better, as in I think it even works, unlike my original. Mind you that I *did* say "something like this (untested)". I consider Chris's solution here "something like this (tested)". :-) I know, I know: untested code never runs. This little gem is actually a pretty nice example of several things: a good time to use pass-by-name, inverting a table, and sorting with a subroutine. I also like the double @{} reference here, because I think to understand it, you really need to get your $'s and @'s and %'s down cold. --tom