Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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

by hippo (Bishop)
on Jun 25, 2021 at 13:41 UTC ( [id://11134274]=note: print w/replies, xml ) Need Help??


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

The general case would be to use a Schwartzian Transform but in this simplistic case for small values of n you can just perform the extractions within the sort:

use strict; use warnings; use Test::More tests => 1; my @in = qw/a-3 a-1 a-2/; my @want = qw/a-1 a-2 a-3/; my @have = sort { ($a =~ /(\d+)/)[0] <=> ($b =~ /(\d+)/)[0] } @in; is_deeply \@have, \@want;

See also the FAQ: How do I sort an array by (anything)?

PS. Here's the same thing but with substr:

use strict; use warnings; use Test::More tests => 1; my @in = qw/a-3 a-1 a-2/; my @want = qw/a-1 a-2 a-3/; my @have = sort { substr ($a, 2) <=> substr ($b, 2) } @in; is_deeply \@have, \@want;

🦛

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:01 UTC
    TYVM that's very helpful. Is the [0] there in case there are more than one number matching like a-1-3 ? TY!
        Thanks for pointing to Sort::Key , seems it covers all use cases of the Schwartzian transform with a short syntax. :)

        The documentation could be simpler tho, by deconstructing the naming convention.

        [|r][|n|i|u]keysort[_inplace] @array

        (Like this the doc seem even to be not logical/ wrong in one case)

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery

        sort key natural IS DA BOMB!! TY TY this made my week :)
        I never saw that Natural sort- you are on fire today all ++ votes! TYVM Have a great weekend- I'm headed off to study your suggestions..

      Not specifically. The regex match is context sensitive, so the brackets around it enforce list context and then the [0] pulls out the first value of that list before the <=> gets a chance to enforce scalar context on it. Example:

      #!/usr/bin/env perl use strict; use warnings; use feature 'say'; my $x = 'a-9'; say "Scalar: " . $x =~ /(\d+)/; say "List: " . ($x =~ /(\d+)/); say "First: " . ($x =~ /(\d+)/)[0];

      Read lots more in the Context tutorial.


      🦛

Log In?
Username:
Password:

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

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

    No recent polls found