Perl 编程/关键字/splice
外观
该splice命令删除由OFFSET和LENGTH指定的元素,用LIST中的元素替换它们(如果有)。删除后,数组会根据需要增长或缩小。如果OFFSET为负数,则它从数组末尾的OFFSET个元素开始。如果没有LENGTH,则从OFFSET开始的所有元素都被删除。如果LENGTH为负数,则从OFFSET开始的所有元素都被删除,除了-LENGTH位于数组末尾的元素。如果没有LENGTH和OFFSET,则所有数组内容都被删除。如果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