Chinaunix首页 | 论坛 | 博客
  • 博客访问: 838244
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-10-14 16:34:06

in the subroutine we just have to compare two variables $a and $b. you dont have to define them. just compare then and return the value as your wish. then call it via sort.

If $a should appear before $b in the final list, the sort subroutine returns −1 to say so. If $b should appear before $a, it returns 1.If the order of $a and $b doesn’t matter, the subroutine returns 0. Why would it not
matter? Perhaps you’re doing a case-insensitive sort and the two strings are fred and
Fred. Or perhaps you’re doing a numeric sort and the two numbers are equal.

  1. my @num = qw /17 1000 04 1.50 3.14159 -10 1.5 4 2001 90210 666/;
  2. sub my_sort{
  3.     if($a > $b){
  4.         1;
  5.     }elsif($a < $b){
  6.         -1;
  7.     }else{
  8.         0;
  9.     }
  10. }
  11. @new = sort my_sort @num;
  12. print "@new";

  13. -10 1.50 1.5 3.14159 04 4 17 666 1000 2001 90210

se the spaceship operator (<=>).  This operator compares two numbers and returns
−1,  0, or  1 as needed to sort them numerically.
  1. sub by_number { $a <=> $b }

  1. sub by_number { $b <=> $a };
  2. @new = sort by_number @num;
  3. print "@new";
90210 2001 1000 666 17 04 4 3.14159 1.50 1.5 -10
 there’s a corre-sponding three-way string-comparison operator: cmp.

  1. sub case_insensitive { "\L$a" cmp "\L$b" }
 by replacing the name of the sort routine
with the entire sort routine “inline,” like so:
  1. my @numbers = sort { $a <=> $b } @some_numbers;


阅读(520) | 评论(0) | 转发(0) |
0

上一篇:index, rindex, substr, sprintf

下一篇:sort hash

给主人留下些什么吧!~~