DavidSzczesniak
12/11/2017 - 3:34 PM

Splice in Perl

Removes and replaces elements from an array given an offset, a length of a list slice, and replacement elements. Both replacing and removing are optional, either can be omitted.

# Example with 2 arguments:
@array = qw(pebbles dino fred barney betty);
@removed = splice @array, 2; # remove fred and everything after, from @array
                             # @removed is qw(fred barney betty)
                             # @array is qw(pebbles dino)

# Example with 3 arguments - specify length:
@array = qw(pebbles dino fred barney betty);
@removed = splice @array, 1, 2; # remove dino, fred (2 elements, starting from index 1)
                                # @removed is qw(dino fred)
                                # @array is qw(pebbles barney betty)

# Example with 4 arguments - replacement list
# note: replacement does not need to be the same size as the splice
@array = qw(pebbes dino fred barney betty);
@removed = splice @array, 1, 2, qw(wilma); # remove dino and fred, add wilma 
                                           # @removed is qw(dino fred)
                                           # @array is qw(pebbles wilma barney betty) 

# Example of just inserting the replacement list, no deletion:
@array = qw(pebbles dino fred barney betty);
@removed splice @array, 1, 0, qw(wilma); # remove nothing, just add wilma
                                         # remove is qw()
                                         # @array is qw(pebbles wilma dino fred barney betty)