Documentation for routine splice assembled from the following pages:
Role: Buf §
From Buf
(Buf) method splice §
method splice( Buf: = 0, ?, * --> Buf)
Substitutes elements of the buffer by other elements
.splice: 0, 3, <3 2 1>;say .raku; # OUTPUT: «Buf.new(3,2,1,2,3,5,8,13,21,34,55,89)»
Class: Array §
From Array
(Array) routine splice §
Defined as:
multi sub splice(, = 0, ?, * --> Array)multi method splice(Array: = 0, ?, * --> 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 = <a b c d e f g>;say .splice(2, 3, <M N O P>); # OUTPUT: «[c d e]» say ; # 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 = <a b c d e f g>;say .splice(6, 4, <M N O P>); # OUTPUT: «[g]» say ; # 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 = <a b c d e f g>;say .splice: *-2, *-1; # OUTPUT: «[f]» say ; # OUTPUT: «[a b c d e g]» my = -> ;my = -> ;say .splice: , ; # OUTPUT: «[e]» say ; # OUTPUT: «[a b c d g]»