加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl sort <=> and cmp

发布时间:2020-12-16 00:39:25 所属栏目:大数据 来源:网络整理
导读: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 instan

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,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. 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读