登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

云之南

风声,雨声,读书声,声声入耳;家事,国事,天下事,事事关心

 
 
 

日志

 
 
关于我

专业背景:计算机科学 研究方向与兴趣: JavaEE-Web软件开发, 生物信息学, 数据挖掘与机器学习, 智能信息系统 目前工作: 基因组, 转录组, NGS高通量数据分析, 生物数据挖掘, 植物系统发育和比较进化基因组学

sort <=> and cmp  

2011-05-10 20:05:07|  分类: perl&bioperl |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

http://blog.sina.com.cn/s/blog_4af3f0d20100etxj.html

sort <=> and cmp

Perl has two operators <=> and cmp,

which are very useful when wishing to sort arrays. $a <=> $b returns -1 if $a is numerically lesser than $b, 1 if it's greater, and zero if they are equal.

cmp does the same for string comparison. For instance the previous example could be re-written as:


[liuguiyou@localhost perl]$ cat sort.pl
#!/usr/bin/perl
use strict;
use warnings;
my @array = (100,5,8,92,-7,34,29,58,8,10,24);
my @sorted_array = sort { $a <=> $b } @array;
print join("<", @sorted_array), "\n";
[liuguiyou@localhost perl]$ ./sort.pl
-7<5<8<8<10<24<29<34<58<92<100

Much more civil, isn't it? The following example, sorts an array of strings in reverse:


[liuguiyou@localhost perl]$ cat sort_chara.pl
#!/usr/bin/perl
use strict;
use warnings;
my @input = (
    "Hello World!",
    "You is all I need.",
    "To be or not to be",
    "There's more than one way to do it.",
    "Absolutely Fabulous",
    "Ci vis pacem, para belum",
    "Give me liberty or give me death.",
    "Linux - Because software problems should not cost money",
);
# Do a case-insensitive sort
my @sorted = sort { lc($a) cmp lc($b); } @input;
print join("\n", @sorted), "\n";
[liuguiyou@localhost perl]$ ./sort_chara.pl
Absolutely Fabulous
Ci vis pacem, para belum
Give me liberty or give me death.
Hello World!
Linux - Because software problems should not cost money
There's more than one way to do it.
To be or not to be
You is all I need.
  评论这张
 
阅读(1208)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018