Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

a bit reversed alphabetical sort 2

Status
Not open for further replies.

2645275

Programmer
Apr 14, 2007
2
0
0
PL
I am using:

@sorted = sort { $a cmp $b } @unsorted;

To sort table elements alphabetically, but when I sort things like:

z
zzz
aaaa
bbb

I become:

aaaa
bbb
z
zzz

Is there a way to make string length a higher priority than the sequence of letters in alphabet, and get result like:

z
bbb
zzz
aaaa
 
using the length() function and the numeric comparison operator "<=>" in the sort will work for the contrived example you posted:

Code:
[blue]@sorted[/blue] = [url=http://perldoc.perl.org/functions/sort.html][black][b]sort[/b][/black][/url] [red]{[/red] [url=http://perldoc.perl.org/functions/length.html][black][b]length[/b][/black][/url][red]([/red][blue]$a[/blue][red])[/red] <=> [black][b]length[/b][/black][red]([/red][blue]$b[/blue][red])[/red] [red]}[/red] [blue]@unsorted[/blue][red];[/red]



------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
And to complete your contrived example:

Code:
[blue]@sorted[/blue] = [url=http://perldoc.perl.org/functions/sort.html][black][b]sort[/b][/black][/url] [red]{[/red] [url=http://perldoc.perl.org/functions/length.html][black][b]length[/b][/black][/url][red]([/red][blue]$a[/blue][red])[/red] <=> [black][b]length[/b][/black][red]([/red][blue]$b[/blue][red])[/red] || [blue]$a[/blue] cmp [blue]$b[/blue] [red]}[/red] [blue]@unsorted[/blue][red];[/red]

- Miller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top