Search code examples
perlsortingrecords

In Perl, how can I sort records using numbers that appear before the first colon (:)?


I have the following sequence of data in Perl:

143:0.0209090909090909 
270:0.0909090909090909 
32:0.0779090909090909 
326:0.3009090909090909

Please, how can I sort them based on the numbers before the colon, to get this as my output?

32:0.0779090909090909
143:0.0209090909090909
270:0.0909090909090909  
326:0.3009090909090909

Solution

  • It does not matter that there are colons there.

    Perl's rules for converting strings to numbers will just do The Right Thing:

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    my @nums = qw(
        143:0.0209090909090909 
        270:0.0909090909090909 
        32:0.0779090909090909 
        326:0.3009090909090909
    );
    
    { no warnings 'numeric';
        @nums = sort {$a <=> $b} @nums;
    }
    
    print "$_\n" for @nums;