my @words = qw(foo bar zorg moo);
my @sorted = sort @words;
# bar, foo, moo, zorg (依 ASCII 碼序)
my @words = qw(foo bar Zorg moo);
my @sorted = sort @words;
# Zorg, bar, foo, moo (大寫 Z 排在小寫前)
sort { $a cmp $b } @array 為預設字串比較。$a、$b 為特殊套裝變數,請勿宣告。
my @sorted = sort { lc($a) cmp lc($b) } @words;
# bar, foo, moo, Zorg
my @nums = (14, 3, 12, 2, 23);
my @sorted = sort { $a <=> $b } @nums; # 太空船操作符
# 2, 3, 12, 14, 23
<=> 數值比較:$a < $b → -1,$a == $b → 0,$a > $b → 1。
# 依檔案大小排序檔名(避免重複 stat)
my @sorted = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [$_, -s $_] } @files;
Perl 5.8+ sort 為穩定排序(相等元素保持原順序),可安全多鍵排序:
my @sorted = sort { $a->{lastname} cmp $b->{lastname} ||
$a->{firstname} cmp $b->{firstname} } @people;
sortSort::Key 模組sort 指令管線)