Ask help for Perl sort customized function

1 view
Skip to first unread message

Fangyuan

unread,
Sep 19, 2011, 3:41:45 AM9/19/11
to perl...@googlegroups.com
大家好,请教一个自定义sort函数的问题。
有一个数组,@a = (1..20, "10+"),我想对这个数组排序,排序的规则是:1)数字优先, "10+"排在数字后面;2)数字按从小到大
我自己写了一个代码,运行没有返回我想要的结果。寻求高手指点一下,谢谢!

my @a = (0..20, "10+");
my @b = sort{
if(m/^\d+$/){
return $a <=> $b;
}
else{
return -1;
}
} @a;
print join(",", @b), "\n";

Fayland Lam

unread,
Sep 19, 2011, 3:47:16 AM9/19/11
to perl...@googlegroups.com
try this.

my @a = (0..20, "10+", 21 .. 25);
@a = reverse(@a);
my @b = sort{
if($a =~ /^\d+$/ and $b =~ /^\d+$/){
return $a <=> $b;
} elsif ($a =~ /^\d+$/) {
return -1;
} elsif ($b =~ /^\d+$/) {
return 1;
} else {
return $a cmp $b;


}
} @a;
print join(",", @b), "\n";

if you have

use warnings;

it will tell you that

Use of uninitialized value $_ in pattern match (m//)

then you know there isn't $_ in sort {}

Thanks

2011/9/19 Fangyuan <chengfan...@gmail.com>:

> --
> 您收到此邮件是因为您订阅了 Google 网上论坛的“PerlChina Mongers 讨论组”论坛。
> 要在网络上查看此讨论,请访问 https://groups.google.com/d/msg/perlchina/-/Jceaq2ltgPQJ
> 要向此网上论坛发帖,请发送电子邮件至 perl...@googlegroups.com
> 要取消订阅此网上论坛,请发送电子邮件至 perlchina+...@googlegroups.com
> 若有更多问题,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问此网上论坛。
>

--
Fayland Lam // http://www.fayland.org/

Robin Lee

unread,
Sep 19, 2011, 3:48:47 AM9/19/11
to perl...@googlegroups.com
my @b = sort{
if ($a !~ /^\d+$/) {
return 1;
}
elsif ($b !~ /^\d+$/) {
return -1;
}
else {
return $a <=> $b;
}
} @a;


2011/9/19 Fangyuan <chengfan...@gmail.com>:

Fangyuan

unread,
Sep 19, 2011, 5:03:49 AM9/19/11
to perl...@googlegroups.com
It works.
Thanks Fayland and Cheese.
Reply all
Reply to author
Forward
0 new messages