| 操作 | 語法 | 陣列長度 | 索引變化 | 元素值 |
|---|---|---|---|---|
| 賦值 undef | $arr[3] = undef | 不變 | 不變 | 該位置變 undef |
| splice 刪除 | splice @arr, 3, 1 | -1 | 後續元素前移 | 元素消失 |
| grep 篩選 | @arr = grep { $_ ne 'target' } @arr | 減少匹配數 | 重新索引 | 移除所有匹配值 |
use Data::Dumper;
my @dwarfs = qw(Doc Grumpy Happy Sleepy Sneezy Dopey Bashful);
print "原始: ", Dumper(\@dwarfs);
$dwarfs[3] = undef; # 第 4 個元素 (Sleepy) 設為 undef
print "賦值 undef 後: ", Dumper(\@dwarfs);
# 等價寫法
undef $dwarfs[5]; # Dopey 設為 undef
print "undef 函式後: ", Dumper(\@dwarfs);
# 輸出:
# 原始: ['Doc','Grumpy','Happy','Sleepy','Sneezy','Dopey','Bashful']
# 賦值 undef 後: ['Doc','Grumpy','Happy',undef,'Sneezy','Dopey','Bashful']
# undef 函式後: ['Doc','Grumpy','Happy',undef,'Sneezy',undef,'Bashful']
my @dwarfs = qw(Doc Grumpy Happy Sleepy Sneezy Dopey Bashful);
splice @dwarfs, 3, 1; # 從索引 3 刪除 1 個元素 (Sleepy)
print "splice 後: ", Dumper(\@dwarfs);
# 刪除多個連續元素
splice @dwarfs, 1, 2; # 刪除 Grumpy, Happy
print "再次 splice: ", Dumper(\@dwarfs);
# 輸出:
# splice 後: ['Doc','Grumpy','Happy','Sneezy','Dopey','Bashful']
# 再次 splice: ['Doc','Sneezy','Dopey','Bashful']
my @dwarfs = qw(Doc Grumpy Happy Sleepy Sneezy Dopey Bashful);
# 移除名稱包含 'y' 的元素
@dwarfs = grep { $_ !~ /y/ } @dwarfs;
print "grep 後: ", Dumper(\@dwarfs);
# 移除特定值 (精確匹配)
@dwarfs = grep { $_ ne 'Doc' } @dwarfs;
print "移除 Doc 後: ", Dumper(\@dwarfs);
# 輸出:
# grep 後: ['Doc','Sleepy','Dopey']
# 移除 Doc 後: ['Sleepy','Dopey']
my @data = (0..9); # 0 1 2 3 4 5 6 7 8 9
my @to_delete = (2, 5, 7); # 要刪除的索引
# 關鍵:從大到小排序索引,避免前面刪除導致後面索引偏移
for my $idx (sort { $b <=> $a } @to_delete) {
splice @data, $idx, 1 if $idx <= $#data;
}
print "結果: @data\n"; # 0 1 3 4 6 8 9
sub delete_first {
my ($arr_ref, $value) = @_;
for my $i (0 .. $#$arr_ref) {
if ($arr_ref->[$i] eq $value) {
splice @$arr_ref, $i, 1;
return 1; # 已刪除
}
}
return 0; # 未找到
}
my @list = qw(a b c b d);
delete_first(\@list, 'b'); # 只刪除第一個 b
print "@list\n"; # a c b d
# 使用 grep 重建陣列 (單次遍歷、單次記憶體分配)
my @large = (1..1_000_000);
@large = grep { $_ % 2 == 0 } @large; # 只保留偶數
# 比迴圈 splice 快數量級
for my $i (0..$#arr) { splice @arr, $i, 1 if ... } 會跳過元素,因索引偏移。解法:逆向迴圈或 grep。undef @arr vs @arr = ():前者釋放記憶體(保留容量),後者長度歸零(保留記憶體供復用)。delete $arr[$i]:僅適用於雜湊,陣列用此會產生「刪除陣列元素已棄用」警告,行為等同 $arr[$i] = undef。
# 環境: Perl 5.34, Intel i7
# splice 迴圈 (逆向): ~1.2 秒
# grep 重建: ~0.03 秒 (快 40 倍!)
# List::MoreUtils::firstidx + splice: ~0.8 秒
結論:大量刪除用 grep 重建;單點/少量精確刪除用 splice;單純標記無效用 undef。