Perl splice Function
The Perl splice function is for arrays and is used to remove, replace or add elements. It has four syntax forms:
splice ARRAY, OFFSET, LENGTH, LIST
splice ARRAY, OFFSET, LENGTH
splice ARRAY, OFFSET
splice ARRAY
where:
- ARRAY is the array to manipulate
- OFFSET is the starting array element to be removed
- LENGTH is the number of elements to be removed
- LIST is an ordered list of elements to replace the removed elements with
The Perl splice function returns:
- in scalar context, the last element removed or undef if no elements are removed
- in list context, the list of elements removed from the array
The array grows or shrinks as necessary. The OFFSET could be negative and then it starts that far from the end of the array. The LENGTH could be negative too and in this case the Perl
splice function will remove the elements from OFFSET onward except for –LENGTH elements at the end of the array.
In this short tutorial, we’ll shortly review every syntax form of this function and you’ll find a few snippets about how to use it in your scripts.
splice ARRAY, OFFSET, LENGTH, LIST
It is the general form of this function and it uses all its arguments. Here’s an example:
# initialize an array
my @array = qw(1 2 3 11 12 10);
my @returnedArray = splice @array, 3, 2, 4..9;
print "\@array = (@array)\n";
print "\@returnedArray = (@returnedArray)\n";
This code produces as output:
@array = (1 2 3 4 5 6 7 8 9 10)
@returnedArray = (11 12)
As you can notice, the Perl
splice function modifies the array passes to it as its first argument. It removes 2 elements (11, 12) starting with the index 3 (the fourth element of the array). Obviously, I assumed that the
$[ special variable is set to 0 (i.e. the first element of the array is 0).
$[ is the index of the first element in an array and can be modified, anyway be cautious if you are tented to alter it.
4..9 is the list argument containing the numbers from 4 to 9 and replaces the two elements removed. The elements removed will be returned in the @returnedArray.
splice ARRAY, OFFSET, LENGTH
In this syntax form, the LIST argument is omitted and you can use this format any time you need to remove a chunk of elements from an array. See the example below for this:
# initialize and fill an array
my @array = qw(1 2 3 4 5 6 7 8 9 10);
my @returnedArray = splice @array, 5, 7;
print "\@array = (@array)\n";
print "\@returnedArray = (@returnedArray)\n";
The output:
@array = (1 2 3 4 5)
@returnedArray = (6 7 8 9 10)
This code will remove the elements of the array starting with the index 5 (the sixth element of the array) and it will try to remove 7 elements. Because there are only 5 elements available, it will remove the elements until the end of the array is reached.
In this syntax form, both the LIST and the LENGTH argument are omitted. In this case the Perl
splice function will remove all the elements from OFFSET onward. If OFFSET is negative, it starts that far from the end of the array. See the following snippet code:
# initialize and fill an array
my @array = qw(1 2 3 4 5 6 7 8 9 10);
# using a positive OFFSET
splice @array, 8;
# the @array is now (1, 2, 3, 4, 5, 6, 7, 8)
# using a negative OFFSET
splice @array, -3;
# the @array is now (1, 2, 3, 4, 5)
In the last example of this code I used a negative OFFSET (-3) – as result the Perl
splice function removed the last 3 elements of the array.
In this format, the Perl
splice function has only one argument – the array variable. In this case it removes all the elements of the array.
my @array = qw(1 2 3 4 5 6 7 8 9 10);
splice @array;
This code will practically empty the array. If you need to empty an array, you may consider other options, too:
@array = (); # or
undef @array; # or
$#array = -1
Using the
undef function could be preferable, because it frees all the memory associated with the array, as if
@array had been declared but never used.
*****
There are also available
other functions that manipulate the
removing, adding and replacing of the elements into an array, such as:
- the shift function that removes the first element of an array
- the unshift function that inserts a list at the beginning of an array
- the pop function that removes the last element of an array
- the push function that appends a list to an array
As you can see, the
shift and
pop function can remove only one element of an array (the first and the last element). You can now use the Perl
slice function to remove a portion of the array, either at the beginning or at the end of the array. And more, you can either insert a list into the middle of an array or remove a portion from an array, starting with any index.
For example, the next snippet code shows you how to delete a portion of an array from the beginning of the array:
my @array = qw(1 2 3 4 5);
splice(@array, 0, 2);
# the array is now: (3, 4, 5)
Or this example that shows you how to insert a list at the beginning of an array:
my @array = qw(6 7 8 9 10);
splice(@array, 0, 0, 1..5);
# the array is now: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
The Perl
splice function starts at the index 0, removes 0 elements and replaces the removed elements with the list 1..5.
Please click here to download the Perl splice script with all the above examples included.
Through these exercises you have the opportunity to try yourself to write some script code where you can use the Perl splice function. These exercises are completely covered in my
Perl Functions for Real Arrays where I show you how to play with this important function in detail.
| 1. | Given a particular array, you can use splice to emulate any of the pop, push, shift and unshift functions. Use the splice function to: a) remove a portion at the beginning of an array b) remove a portion at the end of an array c) insert a list at the beginning of an array
d) add a list at the end of an array |
| 2. | Given two matrices represented as arrays of arrays:my @AoA = (
[ 'a11', 'a14', 'a15', 'a15' ],
[ 'a21', 'a24', 'a25', 'a25' ],
[ 'a31', 'a34', 'a35', 'a35' ],
);
my @AoA1 = (
[ 'a12', 'a13', 'a14'],
[ 'a22', 'a23', 'a24'],
[ 'a32', 'a33', 'a34'],
); replace the second and third columns of the AoA matrix with the columns of the AoA1 matrix. Print the @AoA array after using splice, you need to get:a11 a12 a13 a14 a15
a21 a22 a23 a24 a25
a31 a32 a33 a34 a35 |
| 3. | Given the following arrays of hashes:my @AoH = (
{ name => 'John', age => '21' },
{ name => 'Paul', age => '35' },
{ name => 'Mary', age => '50' },
);
my @tempAoH = (
{ name => 'Anne', age => '32' },
{ name => 'Ken', age => '19' },
);replace the second element of the @AoH array of hashes with the elements stored in the @tempAoH array of hashes. Print the @AoH array as:John is 21 years old.
Anne is 32 years old.
Ken is 19 years old.
Mary is 50 years old. Release the memory occupied by the anonymous hash that was replaced. |
| 4. | Given two matrices: HoA with 3 rows and 3 columns and tempHoA with 3 rows and 2 columns, represent these matrices as hashes of arrays and concatenate the second matrix to the first. Print the %HoA hash of arrays. |
| 5. | Give an example where to use splice to discard the arguments within the body of a subroutine. |
Table of Contents:
A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
Array Size
Array Length
Perl Hashes
Perl Statements
Perl if
Perl unless
Perl switch
Perl while
Perl do-while
Perl until
Perl do-until
Perl for
Perl foreach
Built-in Perl Functions
Functions by Category
String Functions
Regular Expressions and Pattern Matching
List Functions
Array Functions
Hash Functions
Miscellaneous Functions
Functions in alphabetical order
chomp
chop
chr
crypt
defined
delete
each
exists
grep
hex
index
join
keys
lc
lcfirst
length
map
oct
ord
pack
pop
push
q
qq
qw
reverse
rindex
scalar
shift
sort
splice (more)
split
sprintf
substr
tr
uc
ucfirst
undef
unpack
unshift
values
return from Perl splice function to Perl Basics
Would you like to create your own website like this one?
Hit the Alarm Clock!