perl排序

对如下ip进行排序:

134.102.9.87
134.102.5.43
134.102.1.2
134.102.6.7

可以使用如下perl代码实现:

 1 use strict;
 2 use warnings;
 3 use 5.14.2;
 4 
 5 open (my $fh, "<ips.txt") or die "$!";
 6 my @ips;
 7 my $i;
 8 while(<$fh>){
 9     $_ =~ s/^\s+|\s+$//g;
10     $_ =~ s/\n\r|\n|\r//g;
11     $ips[$i++] = $_;
12 }
13 
14 my @r;
15 my @r2;
16 
17 my @ips_sorted = sort {
18               @r  = (split/\./, $a) and
19               @r2 = (split/\./, $b) and
20               $r[0] gt $r2[0] or
21               $r[1] gt $r2[1] or
22               $r[2] gt $r2[2] or
23               $r[3] gt $r2[3]
24               } @ips;
25 foreach my $key (@ips_sorted){
26     say $key;
27 }
28 close $fh;

 

posted @ 2013-05-12 11:08  Richard Zhong  阅读(181)  评论(0编辑  收藏  举报