use List::Util qw(first);
my @names = qw(Wendy Jerry Betty Wendy Alice);
my $match = first { /\bWendy\b/i } @names; # 找到第一個即停止
# 結果: "Wendy"
use List::Util qw(sum);
my $total = sum(1..1000); # 500500
# 比 foreach 循環更簡潔、C 級性能
use List::Util qw(max min);
my $max = max(2, 3, 8, 5, 10); # 10
my $min = min(2, 3, 8, 5, 10); # 2
# 字符串比較
use List::Util qw(maxstr minstr);
my $max_str = maxstr(qw/JERRY BETTY ALICE FRED BARNEY jerry/); # "jerry" (字典序)
use List::Util qw(shuffle);
my @shuffled = shuffle(1..10); # 如: 3 9 8 5 6 4 1 10 2 7
my @shuffled_names = shuffle('A'..'G');
use List::MoreUtils qw(none any all);
my @numbers = qw(7 4 1 3 78);
if (none { $_ > 100 } @numbers) { print "無元素 > 100\n"; }
elsif (any { $_ > 50 } @numbers) { print "有元素 > 50\n"; }
elsif (all { $_ < 10 } @numbers) { print "所有元素 < 10\n"; }
類似 grep 語法,但語義更清晰、短路求值(any/all 遇到結果立即返回)
use List::MoreUtils qw(natatime);
my @names1 = qw(Alice Bob Carly);
my @names2 = qw(David Edward Foo);
my $iter = natatime(2, @names1, @names2); # 每次取 2 個
while (my @batch = $iter->()) {
print "Got @batch\n";
}
# 輸出:
# Got Alice Bob
# Got Carly David
# Got Edward Foo
use List::MoreUtils qw(mesh);
my @a = 'A'..'D';
my @b = 1..4;
my @c = qw(jerry alice wendy);
my @merged = mesh(@a, @b, @c);
# 結果: A, 1, jerry, B, 2, alice, C, 3, wendy, D, 4
輪流從每個列表取一個元素,直到最長列表耗盡
use List::MoreUtils qw(insert_after);
my @list = qw(This is a list);
insert_after { $_ eq 'a' } "longer" => @list;
# 結果: This is a longer list
use List::MoreUtils qw(pairwise);
my @m = 1..4;
my @n = 100..103;
my @result = pairwise { ($a * $a) + $b } @m, @n;
# 結果: 101, 105, 111, 119
# 計算: 1*1+100, 2*2+101, 3*3+102, 4*4+103
| 操作 | 手寫循環 | 優勢 | |
|---|---|---|---|
| 求和 | foreach 累加 | sum() | C 實現、SIMD 優化可能 |
| 最大值 | foreach 比較 | max() | 單次遍歷、無臨時變量 |
| 隨機打亂 | Fisher-Yates 手寫 | shuffle() | 標準算法、邊界情況正確 |
| 條件檢查 | foreach + flag | any/all/none | 短路求值、語義清晰 |
use List::Util qw(uniq);
use List::MoreUtils qw(frequency);
my @log_lines = <$fh>;
my @error_codes = map { /ERROR (\d+)/ } @log_lines; # 提取錯誤碼
my @unique_codes = uniq(@error_codes); # 去重
my %freq = frequency(@error_codes); # 頻率統計
for my $code (sort { $freq{$b} <=> $freq{$a} } keys %freq) {
print "$code: $freq{$code}\n";
}
use List::MoreUtils qw(mesh);
my @headers = qw(ID Name Score);
my @ids = 1..100;
my @names = map { "User$_" } 1..100;
my @scores = map { int(rand(100)) } 1..100;
my @rows = mesh(@ids, @names, @scores); # 交織
# 寫入 CSV: 每 3 個元素一行
# List::Util 核心模塊,無需安裝
use List::Util qw(first sum max min shuffle uniq);
# List::MoreUtils 需安裝
cpanm List::MoreUtils
# 或
cpan List::MoreUtils
use List::MoreUtils qw(none any all natatime mesh insert_after pairwise frequency uniq);
List::Util 和 List::MoreUtils 將複雜的列表算法封裝為簡潔的函數調用,底層 C 實現保證極致性能。掌握 first/sum/max/min/shuffle、none/any/all、natatime/mesh/insert_after/pairwise 等核心函數,能以聲明式風格解決 90% 的列表處理需求,代碼更短、更快、更難出錯。這正是 Perl「電池內含」哲學的體現:複雜性下沉到庫,業務邏輯保持純粹。