Perl Programming/Keywords/splice

Previous: sort Keywords Next: split

The splice keyword

edit

The splice command removes the elements designated by OFFSET and LENGTH to replace them with the elements of LIST, if any. After deletion, the array grows or shrinks as necessary. If OFFSET is negative, it starts OFFSET elements away from the end of the array. Without LENGTH, everything from OFFSET onward is removed. If LENGTH is negative, everything from OFFSET onward is removed except -LENGTH at the array end. Without both LENGTH and OFFSET, all the array contents are removed. If OFFSET is past the end of the array and a LENGTH was given, Perl issues a warning, and splices at the end of the array.

splice can be used to implement n-ary queue processing. With Perl 5.14.0, splice can also accept an EXPRESSION with an reference to an unblessed array.

Syntax

edit
  splice ARRAY or EXPRESSION, OFFSET, LENGTH, LIST
  splice ARRAY or EXPRESSION, OFFSET, LENGTH
  splice ARRAY or EXPRESSION, OFFSET
  splice ARRAY or EXPRESSION

Examples

edit
 
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";
}
returns
key => bar 22
key => bar 22
delete $hash{foo}
11
22
@array = delete @hash{qw(foo baz)}
0

See also

edit
Previous: sort Keywords Next: split