Movatterモバイル変換


[0]ホーム

URL:


functions /splice
(source,CPAN)
You are viewing the version of this documentation from Perl 5.18.2.View the latest version
#splice ARRAY or EXPR,OFFSET,LENGTH,LIST
#splice ARRAY or EXPR,OFFSET,LENGTH
#splice ARRAY or EXPR,OFFSET
#splice ARRAY or 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, orundef 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, Perl issues a warning, and splices at the end of the array.

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

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

Example, assuming array lengths are passed before arrays:

sub aeq {  # compare two list values    my(@a) = splice(@_,0,shift);    my(@b) = splice(@_,0,shift);    return 0 unless @a == @b;  # same len?    while (@a) {        return 0 if pop(@a) ne pop(@b);    }    return 1;}if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }

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 ofsplice 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 workonly on Perls of a recent vintage:

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

Perldoc Browser is maintained by Dan Book (DBOOK). Please contact him via theGitHub issue tracker oremail regarding any issues with the site itself, search, or rendering of documentation.

The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via thePerl issue tracker, themailing list, orIRC to report any issues with the contents or format of the documentation.


[8]ページ先頭

©2009-2026 Movatter.jp