|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stay one step ahead of the competition. Evaluate and give feedback
on some of the hottest web development tools on the market today.
Make your opinion heard! Click
Here
|
|
#1
|
|||
|
|||
|
I'm trying to sort an array by a specific field in the array. I can't get this work at all.
Here's a sample line in the array named @results. <tr><td><a href=mailto:name1@myemail.com>Name 1</a></td><td>5834</td><td align=right>+1 510-555-5555</td></tr> I want to sort on the field "Name1". So I know I have to split that one out. So here's my code to split out that field. ================= foreach $line (sort ({ (split("/\>/", $a))[3] <=> (split("/\/", $b))[3] } @results)) { print "$line"; } ================= Any help would be greatly appreciated. Guyle Taber gtaber@geoworks.com |
|
#2
|
||||
|
||||
|
Here's a sort of generalized chunk of code you can use to do that, and used
in lots of other situations, too. #You have an array. Each line of the array is 1 record. #The &error() returns info to the user if the open fails. You write this. open (CUSTFILE, "$db") or &error('Error opening database file'); @lines = <CUSTFILE>; close(CUSTFILE); #Decide which field you want to sort on. Start counting at 0. #You want the third: $field = 2; #What separators your fields? Pretend it's a space. Might be ||. $sep = ' '; #Use Perl sort, giving it a flexible sorting subroutine #that uses the values of $sep and $field to figure out what the field #delimiter is and which field to use (0,1,2,...) @lines = sort byDictd @lines; sub byDictField { (split(/$sep/, lc($a)))[$field] cmp (split(/$sep/, lc($b)))[$field]; #cmp for comparing words #dictionary order, ignoring case (w/o lc(), get ASCII order) } sub byNumField { (split(/$sep/, $a))[$field] <=> (split(/$sep/, $b))[$field]; #<=> for comparing numbers as values, notwords } Pretty flexible, and for many programs, it means you write the sort routine once and just set $sep and $field as needed. I dunno about you, but I have cases where records are returned sorted by date, by last name, by title, and all sort of crap. Hope this helps ![]() Mickalo
__________________
Thunder Rain Internet Publishing Custom Programming & Database development Providing Personal/Business Internet Solutions that work! |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Perl Programming > Sort Array on Specific Variable |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|