Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: How can I do a numeric sort on a substring?

by syphilis (Archbishop)
on Jun 25, 2021 at 14:07 UTC ( [id://11134277]=note: print w/replies, xml ) Need Help??


in reply to How can I do a numeric sort on a substring?

I want to sort on the numeric part using $a <=> $b

Here's my guess:
use strict; use warnings; my @data = qw(a-2 a-10 a-9 a-8 a-0 a-1 a-3 a-6 a-5 a-4 a-7); my @sorted = map {'a-' . $_} sort {$b <=> $a} map {substr($_, 2, lengt +h($_) -2) } @data; print "@sorted\n"; __END__ Outputs: a-10 a-9 a-8 a-7 a-6 a-5 a-4 a-3 a-2 a-1 a-0
If you want them to appear in the reverse order, instead do:
my @sorted = map {'a-' . $_} sort {$a <=> $b} map {substr($_, 2, lengt +h($_) -2) } @data;
Cheers,
Rob

Replies are listed 'Best First'.
Re^2: How can I do a numeric sort on a substring?
by misterperl (Pilgrim) on Jun 25, 2021 at 14:13 UTC
    nicely done Rob! ++ vote also love it..

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11134277]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2024-04-16 18:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found