perl sort <=> and cmp
来源:互联网 发布:ubuntu terminal 配色 编辑:程序博客网 时间:2024/05/27 20:51
Perlhas two operators <=> andcmp,
which are veryuseful when wishing to sort arrays. $a<=> $b returns -1 if $ais numerically lesser than $b, 1 if it's greater, and zeroif they are equal.
cmp does the same for string comparison.For instance the previous example could be re-writtenas:
[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
Muchmore civil, isn't it? The following example, sorts an array ofstrings 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.
- perl sort <=> and cmp
- em的错误 <转载>
- ORADEBUG DOC <转载>
- < >
- Why ASMLIB and why not? <转载…
-  
-
- HTML 5 <header> 标签
- HTML 5 <hgroup> 标签
- HTML 5 <button> 标签
- <转> 联合早报 科学发展…
- OPEN_CURSOR and v$open_cursor <f…
- Unterminated <%@ page tag
- HTML <a></a&…
- 技术 < 商业
- HTML <table> 标签的 frame 属性
- HTML 5 <input> required 属性
- HTML 5 <input> disabled 属性
- putty使用教程
- java对cookie的操作
- nagios+pnp4nagios安装
- PHP JSON extension not avaliabl…
- perl学习笔记
- perl sort <=> and cmp
- perl中数组函数详解:join和split…
- 使用javascript动态管理css
- curl监控站点响应时间
- ksh学习笔记
- This system is not registered wi…
- linux终端命令精选
- Linux(ubuntu)赋予用户sudo权限
- linux top命令详解