Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1306895
  • 博文数量: 213
  • 博客积分: 7590
  • 博客等级: 少将
  • 技术积分: 2185
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-31 17:31
个人简介

热爱开源,热爱linux

文章分类

全部博文(213)

文章存档

2018年(4)

2017年(1)

2015年(1)

2014年(5)

2013年(2)

2012年(2)

2011年(21)

2010年(82)

2009年(72)

2008年(23)

分类: LINUX

2011-01-03 11:01:31

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.


下面有一个例子计算几个不同的学生的平均成绩,例如ceagle 计算他4门课的平均成绩

beyond    huaxue    98
jack    huaxue    90
tom    huaxue    70
ceagle    huaxue    99
beyond    shuxue    77
jack    shuxue    99
tom    shuxue    80
ceagle    shuxue    88
beyond    dili    77
jack    dili    99
tom    dili    80
ceagle    dili    88
beyond    wuli    77
jack    wuli    99
tom    wuli    80
ceagle    wuli    88

使用perl实现如下

#!/usr/bin/perl -w

use strict;
my %hash=();
open my $file ,'<','data' or die "$!\n";
while (<$file>) {
    chomp;
    my ($name,$score)=$_=~/(\w+)\s+\w+\s+(\d+)/;
    $hash{$name}+=$score;
}
close($file);
for (sort{$a cmp $b} keys %hash) {
    print "$_\t";
    print $hash{$_}/4,"\n";
}


阅读(3185) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~