In Array§

See primary documentation in context for routine splice

multi        splice(@list,   $start = 0$elems?*@replacement --> Array)
multi method splice(Array:D: $start = 0$elems?*@replacement --> Array)

Deletes $elems elements starting from index $start from the Array, returns them and replaces them by @replacement. If $elems is omitted or is larger than the number of elements starting from $start, all the elements starting from index $start are deleted. If both $start and $elems are omitted, all elements are deleted from the Array and returned.

Each of $start and $elems can be specified as a Whatever or as a Callable that returns an Int-compatible value: this returned value is then used as the corresponding argument to the splice routine.

A Whatever $start uses the number of elements of @list (or invocant). A Callable $start is called with one argument—the number of elements in @list (or self).

A Whatever $elems deletes from $start to end of @list (or self) (same as no $elems). A Callable $elems is called with one argument—the number of elements in @list (or self) minus the value of $start.

Example:

my @foo = <a b c d e f g>;
say @foo.splice(23, <M N O P>);        # OUTPUT: «[c d e]␤» 
say @foo;                                # OUTPUT: «[a b M N O P f g]␤»

It can be used to extend an array by simply splicing in more elements than the current size (since version 6.d)

my @foo = <a b c d e f g>;
say @foo.splice(64, <M N O P>);       # OUTPUT: «[g]␤» 
say @foo;                               # OUTPUT: «[a b c d e f M N O P]␤» 

The following equivalences hold (assuming that @a.elems ≥ $i):

@a.push($x, $y)      @a.splice: *  , *, $x, $y
@a.pop               @a.splice: *-1,
@a.shift             @a.splice: 0  , 1,
@a.unshift($x, $y)   @a.splice: 0  , 0, $x, $y
@a[$i] = $y          @a.splice: $i , 1, $y,

As mentioned above, a Whatever or Callable object can be provided for both the $start and $elems parameters. For example, we could use either of them to remove the second to last element from an array provided it's large enough to have one:

my @foo = <a b c d e f g>;
say @foo.splice: *-2*-1;           # OUTPUT: «[f]␤» 
say @foo;                            # OUTPUT: «[a b c d e g]␤» 
 
my &start     = -> $n { $n - 2 };
my &elems-num = -> $m { $m - 1 };
say @foo.splice: &start&elems-num# OUTPUT: «[e]␤» 
say @foo;                            # OUTPUT: «[a b c d g]␤»

In role Buf§

See primary documentation in context for method splice

method spliceBuf:D: $start = 0$elems?*@replacement --> Buf)

Substitutes elements of the buffer by other elements, returning a buffer with the removed elements.

my $ = Buf.new11235 );
say $.splice:  03, <3 2 1>;  # OUTPUT: «Buf:0x<01 01 02>␤» 
say $.raku;                    # OUTPUT: «Buf.new(3,2,1,3,5)␤»