如何对perl进行字母数字排序? [英] How to do alpha numeric sort perl?

查看:305
本文介绍了如何对perl进行字母数字排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的文件:

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  
89,11q13.1  
90,2q23-q24  
91,12q13  
92,2q22.3  
93,3p22  
94,12q11-q14  
95,3p21.1  
97,14q24.3  
98,2p16.2  

我想根据第二列对它们进行排序.并且第一列也应相应地更改.当您在perl中使用sort命令时,它不会执行此操作,因为它说它不是数字.有没有办法在perl中按数字对事物进行排序?

And I want to sort them based on second column. And the first column should change accordingly too. When you use sort command in perl, it doesn't do it because it says its not numeric. Is there a way to sort things alpha numerically in perl?

谢谢.

推荐答案

如果您阅读有关排序,您将看到不需要在Perl中进行数字排序.您也可以进行字符串比较.

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;

但这仍然给您带来问题,例如19q将在6p之前排序.因此,您可以编写自己的排序函数,该函数可以在进行比较之前进行所需的任何转换.

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;
}

这篇关于如何对perl进行字母数字排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆