Chinaunix首页 | 论坛 | 博客
  • 博客访问: 408446
  • 博文数量: 117
  • 博客积分: 5235
  • 博客等级: 大校
  • 技术积分: 1775
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-12 15:51
文章分类

全部博文(117)

文章存档

2012年(9)

2011年(2)

2010年(21)

2009年(13)

2008年(72)

我的朋友

分类:

2008-07-21 14:15:57

背景:
    在读代码时发现一个奇怪的东西,$a<=>$b.应用于sort函数,于是有说一下的必要.
 
正文:
 
1.基本语法
@sorted = sort {regular} @nosort;
 
2.一般用法
@sorted = sort(@nosort);    >>>按字符顺序从小到大
@sorted = reverse sort(@nosort); >>>从大到小
 
3.标准用法
<=>

cmp

$a<=>$b   >>>数字从大到小
$a cmp $b >>>字母从大到小
 
$b <=> $a >>>数字从小到大
$b cmp $a >>>字母从小到大
 
@sorted = sort { $a <=> $b } @not_sorted # numerical sort
or
@sorted = sort { $a cmp $b } @not_sorted # ASCII-betical sort
or better
@sorted = sort { lc($a) cmp lc($b) } @not_sorted # alphabetical sort
 
@sorted = sort { $hash{$a} cmp $hash{$b} } keys %hash;
Get a reverse sort of a list
@sorted = sort { $b cmp $a } @list;
or
@sorted = reverse sort { $a cmp $b } @list;
 
总结:
也许使用标准方法才能看出sort的真正设计意图.
阅读(1344) | 评论(1) | 转发(0) |
0

上一篇:奇怪的$a<=>$b

下一篇:文件状态判断

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

chinaunix网友2008-09-16 14:13:47

$a<=>$b >>>数字从大到小 $a cmp $b >>>字母从大到小 $b <=> $a >>>数字从小到大 $b cmp $a >>>字母从小到大 这个写反了哦