Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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

by AnomalousMonk (Archbishop)
on Jun 25, 2021 at 16:22 UTC ( [id://11134288]=note: print w/replies, xml ) Need Help??


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

Here's another example of the Schwartzian mentioned earlier. I've written it as a "one-liner" although that's not the form I'd prefer for production code for reasons of readability/maintainability. I've added more test values in different formats to illustrate the effects of the regex that is used.

Win8 Strawberry 5.8.9.5 (32) Fri 06/25/2021 11:50:17 C:\@Work\Perl\monks >perl use strict; use warnings; use Test::More tests => 1; 1..1 my @in = qw/a-3 21-2 a-2 bb-10 c--11-1 a-1 def-2-99/; my @want = qw/a-1 a-2 def-2-99 a-3 bb-10 c--11-1 21-2/; my @got = map $_->[0], sort { $a->[1] <=> $b->[1] } map [ $_, /\d+/g ] +, @in; is_deeply \@got, \@want; ^Z ok 1
Another consideration when sorting is "stability." See the discussion of this here and in the sort pragma. See also Guttman and Rosler's A Fresh Look at Efficient Perl Sorting for lots more info on Perl sorting.


Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2024-04-19 22:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found