How to do alpha numeric sort perl?

前端 未结 3 377
迷失自我
迷失自我 2021-01-28 02:46

I have a file which looks like this:

80,1p21  
81,19q13  
82,6p12.3  
83,Xp11.22  
84,3pter-q21  
86,3q26.33  
87,14q24.1-q24.2|14q24|14q22-q24  
88,1q42-q43  
8         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-28 03:36

    If you read the documentation for sort, you'll see that you don't need to do a numeric sort in Perl. You can do string comparisons too.

    @sorted = sort { $a cmp $b } @unsorted;
    

    But that still leaves you with a problem as, for example, 19q will sort before 6p. So you can write your own sort function which can make whatever transformations you want before doing the comparison.

    @sorted = sort my_complex_sort @unsorted;
    
    sub my_complex_sort {
      # code that compares $a and $b and returns -1, 0 or 1 as appropriate
      # It's probably best in most cases to do the actual comparison using cmp or <=>
    
      # Extract the digits following the first comma
      my ($number_a) = $a =~ /,(\d+)/;
      my ($number_b) = $b =~ /,(\d+)/;
    
      # Extract the letter following those digits
      my ($letter_a) = $a =~ /,\d+(a-z)/;
      my ($letter_b) = $b =~ /,\d+(a-z)/;
    
      # Compare and return
      return $number_a <=> $number_b or $letter_a cmp $letter_b;
    }
    

提交回复
热议问题