2011年10月7日 星期五

perl sorting


  • sort SUBNAME LIST
  • sort BLOCK LIST
  • sort LIST

#sortTech.pl
@arr1 = (1..2);
@arr2 = (3..5);
sub sortMethod{
    $a<=>$b;
}
sub sortInverse{
    $b<=>$a;
}

@result = sort sortMethod   @arr1,@arr2;
@inverseResult = sort sortInverse @arr1,@arr2;
#等價於@inverseResult = reverse sort @arr1,@arr2 ;

print "Use sortMethod:  @result\n";
print "Use sortInverse: @inverseResult\n";

@wordList = qw /one two three four/ ;
@sortedList =  sort {$a cmp $b} @wordList;
print "sortedList:@sortedList\n";
@sortAllKind = sort {$a cmp $b } @wordList,"hello";
print "sortedAllKind:@sortAllKind\n";
@sorted = reverse sort { $a cmp $b } @list;


#sortAlgo.pl

use sort 'stable';
use sort '_quicksort';
no sort 'stable';

@old1 =qw /"hello" "world" "stayhigh"/ ;
@old2 =qw /1 3 2/ ;
@old = (@old1,@old2); # 陣列合併
print "\@old : @old\n";

my @new = sort {
        ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0]
            ||
        uc($a)  cmp  uc($b)
    } @old;

print "排序結果為:@new";

沒有留言:

張貼留言