跳轉到內容

Perl 程式設計/關鍵字/splice

來自華夏公益教科書,開放的書籍,面向開放的世界
上一個:sort 關鍵字 下一個:split

splice關鍵字

[編輯 | 編輯原始碼]

splice命令刪除由OFFSETLENGTH指定的元素,用LIST中的元素替換它們(如果有)。刪除後,陣列會根據需要增長或縮小。如果OFFSET為負數,則它從陣列末尾的OFFSET個元素開始。如果沒有LENGTH,則從OFFSET開始的所有元素都被刪除。如果LENGTH為負數,則從OFFSET開始的所有元素都被刪除,除了-LENGTH位於陣列末尾的元素。如果沒有LENGTHOFFSET,則所有陣列內容都被刪除。如果OFFSET超過了陣列末尾,並且提供了LENGTH,Perl 會發出警告,並在陣列末尾進行拼接。

splice可用於實現 n 進位制佇列處理。在 Perl 5.14.0 中,splice還可以接受一個EXPRESSION,它包含對未祝福陣列的引用。

  splice ARRAY or EXPRESSION, OFFSET, LENGTH, LIST
  splice ARRAY or EXPRESSION, OFFSET, LENGTH
  splice ARRAY or EXPRESSION, OFFSET
  splice ARRAY or EXPRESSION
use 5.10.0;

%hash = (foo => 11, bar => 22, baz => 33);

for (($key, $element) = each %hash) {
  print "key => " . $key . " " . $element . "\n";
}

say 'delete $hash{foo}';
$scalar = delete $hash{foo}; # $scalar is 11

print $scalar . "\n";
$scalar = delete @hash{qw(foo bar)}; # $scalar is 22

print $scalar . "\n";
@array = delete @hash{qw(foo baz)}; # @array is (undef, 33)

say '@array = delete @hash{qw(foo baz)}';
for ($element = each @array) {
 print $element . "\n";
}
返回
key => bar 22
key => bar 22
delete $hash{foo}
11
22
@array = delete @hash{qw(foo baz)}
0

另請參閱

[編輯 | 編輯原始碼]
上一個:sort 關鍵字 下一個:split
華夏公益教科書