@SortList = (1,2,3,4,5,6,7,8,9,10,11);
print "SORT前\n";
$, = ", ";
print @SortList;
print "\n";
#文字列で昇順
@SortedList = sort @SortList;
$, = ", ";
print "文字列で昇順\n";
print @SortedList;
print "\n";
#文字列で昇順(省略しないとき)
@SortedList = sort { $a cmp $b } @SortList;
#他の出力の仕方
print "文字列で昇順(省略しないとき)\n";
print join(', ', @SortedList);
print "\n";
#文字列で降順
@SortedList = sort { $b cmp $a } @SortList;
print "文字列で降順\n";
print join(', ', @SortedList);
print "\n";
#文字列で降順(Reverse使用)
@SortedList = reverse sort { $a cmp $b } @SortList;
print "文字列で降順(Reverse使用)\n";
print join(', ', @SortedList);
print "\n";
#数値で昇順
@SortedList = sort { $a <=> $b } @SortList;
print "数値で昇順\n";
print join(', ', @SortedList);
print "\n";
#数値で降順
@SortedList = sort { $b <=> $a } @SortList;
print "数値で降順\n";
print join(', ', @SortedList);
print "\n";
#数値で昇順(サブルーチン使用)
@SortedList = sort byNumber @SortList;
print "数値で昇順(サブルーチン使用)\n";
print join(', ', @SortedList);
print "\n";
sub byNumber{
$a <=> $b;
}
#数値で昇順(サブルーチン内省略しない)
@SortedList = sort byNumber2 @SortList;
print "数値で昇順(サブルーチン内省略しない)\n";
print join(', ', @SortedList);
print "\n";
sub byNumber2{
if ($a < $b){
return -1;
}elsif ($a == $b){
return 0;
}elsif ($a > $b){
return 1;
}
}
#文字列で昇順(サブルーチン内省略しない)
@SortedList = sort byNumber3 @SortList;
print "文字列で昇順(サブルーチン内省略しない)\n";
print join(', ', @SortedList);
print "\n";
sub byNumber3{
if ($a lt $b){
return -1;
}elsif ($a eq $b){
return 0;
}elsif ($a gt $b){
return 1;
}
}
#好きなように(偶数奇数に分ける)
@SortedList = sort byNumber4 @SortList;
print "好きなように(偶数奇数に分ける)\n";
print join(', ', @SortedList);
print "\n";
sub byNumber4{
if ($a%2 < $b%2){
return -1;
}elsif ($a%2 == $b%2){
return 0;
}elsif ($a%2 > $b%2){
return 1;
}
}
|