Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: How can I sort my array numerically on part of the string?

by misterperl (Pilgrim)
on Dec 01, 2020 at 21:22 UTC ( [id://11124485]=note: print w/replies, xml ) Need Help??


in reply to How can I sort my array numerically on part of the string?

I don't like this as much as your hash approach which has appeal, but this seems to work:

my @sorted = sort byPrefix @s; # sort the keys numerically sub byPrefix { # make copies so originals are preserved my ( $x, $y ) = ( $a, $b ); # get prefixes $x =~ s/:.+//; $y =~ s/:.+//; # RV $_=0; $x < $y && $_--; $x > $y && $_++; $_; }

Replies are listed 'Best First'.
Re^2: How can I sort my array numerically on part of the string?
by AnomalousMonk (Archbishop) on Dec 01, 2020 at 21:55 UTC
    $_=0;

    Shouldn't this be
        local $_ = 0;
    to avoid global variable side effects (see local)?

    $_=0; $x < $y && $_--; $x > $y && $_++; $_;

    And how does this code differ in effect from
        $x <=> $y;
    (see <=> in Equality Operators in perlop)?

    (And a small point, but , (comma) is used as the delimiter in the OPed example data instead of : (colon), which you use in the s/:.+// extraction substitutions.)


    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://11124485]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (1)
As of 2024-04-25 00:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found