Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

Tools

splice

Perl 5 version 22.0 documentation
Recently read

splice

  • splice ARRAY,OFFSET,LENGTH,LIST

  • splice ARRAY,OFFSET,LENGTH
  • splice ARRAY,OFFSET
  • splice ARRAY
  • splice EXPR,OFFSET,LENGTH,LIST
  • splice EXPR,OFFSET,LENGTH
  • splice EXPR,OFFSET
  • splice EXPR

    Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any. In list context, returns the elements removed from the array. In scalar context, returns the last element removed, or undef if no elements are removed. The array grows or shrinks as necessary. If OFFSET is negative then it starts that far from the end of the array. If LENGTH is omitted, removes everything from OFFSET onward. If LENGTH is negative, removes the elements from OFFSET onward except for -LENGTH elements at the end of the array. If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is past the end of the array and a LENGTH was provided, Perl issues a warning, and splices at the end of the array.

    The following equivalences hold (assuming $#a >= $i )

    1. push(@a,$x,$y) splice(@a,@a,0,$x,$y)
    2. pop(@a) splice(@a,-1)
    3. shift(@a) splice(@a,0,1)
    4. unshift(@a,$x,$y) splice(@a,0,0,$x,$y)
    5. $a[$i] = $y splice(@a,$i,1,$y)

    splice can be used, for example, to implement n-ary queue processing:

    1. sub nary_print {
    2. my $n = shift;
    3. while (my @next_n = splice @_, 0, $n) {
    4. say join q{ -- }, @next_n;
    5. }
    6. }
    7. nary_print(3, qw(a b c d e f g h));
    8. # prints:
    9. # a -- b -- c
    10. # d -- e -- f
    11. # g -- h

    Starting with Perl 5.14, splice can take scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of splice is considered highly experimental. The exact behaviour may change in a future version of Perl.

    To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work only on Perls of a recent vintage:

    1. use 5.014; # so push/pop/etc work on scalars (experimental)