Alexander75 has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I need to sort this king of string : Lee Morgan : 20 Clifford Brown : 3 Freddie Hubbard : 6 The way that C.B goes before L.M and F.H before L.M I really have no idea of to make it First I wanted to use a module that is able to find numbers, but I didn't find one After I wanted to use regexp But however the real problem reminds to know how to sort, because sort function only takes like just one kind of values

Replies are listed 'Best First'.
Re: Sort string according to numbers in it
by jeffa (Bishop) on Apr 30, 2015 at 17:58 UTC

    You aren't very clear on precisely what your output should be. It sounds like you want an ascending sort based on the number next to the name. This will do that:

    use strict; use warnings; my $str = 'Lee Morgan : 20 Clifford Brown : 3 Freddie Hubbard : 6 '; my @data = map {[ split /\s+:\s+/, $_]} split /\n/, $str; for (sort { $a->[1] <=> $b->[1] } @data) { print join( ' : ', @$_ ), $/; }

    You can break the string up with split into a 2D array and then sorting by that number becomes much easier.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      Jeffa, thanks you so much so much so much. I just put on a "reverse" because I needed from bigger to smaller, and now that gives me exactly what I wanted. I will study this little code and keep it in mind. Thank you

        If you need descending order, rather than wastefully filtering the sorted results through reverse you can instead just swap $a and $b:

        for (sort { $b->[1] <=> $a->[1] } @data) { print join( ' : ', @$_ ), $/; }
        And since we are on the topic, be sure and check out the Schwartzian Transform.

        jeffa

        L-LL-L--L-LL-L--L-LL-L--
        -R--R-RR-R--R-RR-R--R-RR
        B--B--B--B--B--B--B--B--
        H---H---H---H---H---H---
        (the triplet paradiddle with high-hat)
        
Re: Sort string according to numbers in it
by toolic (Bishop) on Apr 30, 2015 at 18:00 UTC

      ... and there are also some good tutorials.


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