perl sort   <=> and cmp
2013-01-14 14:19
323 查看
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:
Much
more civil, isn't it? The following example, sorts an array of
strings in reverse:
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.
相关文章推荐
- perl sort <=> and cmp
- The Difference between <resource-ref> and <resource-env-ref>,the title should be long...
- <!--配置中文乱码的过滤器 -->
- This tag and its children can be replaced by one <TextView/> and a compound drawable
-  |"|&|<|>等html字符转义
- 如果赌博拒收美元 <转>
-  |"|&|<|>等html字符转义
- 模板类 template <class T> sort
- " & < > 等html字符转义
- 服务名、实例名和数据库名 <转载>
- HTML常用的转义字符(" & < > )
- Note On <You Don't Know JS - Scope and Closures>
- perl 数字<->字符串及其进制间的转换
- poe.xml 出现web.xml is missing and <failOnMissingWebXml> is set to true的错误
- <转>Alibaba-AndFix Bug 热修复 以及添加到自己项目中
- UNITY3D shader学习心得<三> Vertex and Fragment Shader
- qtp&nbsp;问题汇总(不断更新)&lt;二&gt;
- <LeetCode OJ> 106. Construct Binary Tree from Inorder and Postorder Traversal
- Perl <> 符号
- perl 高级操作符 <=>