Perl array splice() function - Quick Tutorial

How to use the array splice() function

Young man sitting at desk, using laptop and drinking coffee
AAGAMIA/The Image Bank/Getty Images
 @LIST = splice(@ARRAY, OFFSET, LENGTH, @REPLACE_WITH); 
Perl's splice() function is used to cut out and return a chunk or portion of an array. The portion that is cut out starts at the OFFSET element of the array and continues for LENGTH elements. If the LENGTH is not specified, it will cut to the end of the array.
 @myNames = ('Jacob', 'Michael', 'Joshua', 'Matthew', 'Ethan', 'Andrew');
 @someNames = splice(@myNames, 1, 3); 
Think of the @myNames array as a row of numbered boxes, going from left to right, numbered starting with a zero. The splice() function would cut a chunk out of the @myNames array starting with the element in the #1 position (in this case, Michael) and ending 3 elements later at Matthew. The value of @someNames then becomes ('Michael', 'Joshua', 'Matthew'), and @myNames is shortened to ('Jacob', 'Ethan', 'Andrew').

As an option, you can replace the portion removed with another array by passing it in the REPLACE_WITH argument.

 @myNames = ('Jacob', 'Michael', 'Joshua', 'Matthew', 'Ethan', 'Andrew');
 @moreName = ('Daniel', 'William', 'Joseph');
 @someNames = splice(@myNames, 1, 3, @moreName); 
In the above example, the splice() function would cut a chunk out of the @myNames array starting with the element in the #1 position (in this case, Michael and ending 3 elements later at Matthew. It then replaces those names with the contents of the @moreNames array.
The value of @someNames then becomes ('Michael', 'Joshua', 'Matthew'), and @myNames is changed to ('Jacob', 'Daniel', 'William', 'Joseph', 'Ethan', 'Andrew').
Format
mla apa chicago
Your Citation
Brown, Kirk. "Perl array splice() function - Quick Tutorial." ThoughtCo, Nov. 25, 2014, thoughtco.com/perl-array-splice-function-quick-tutorial-2641163. Brown, Kirk. (2014, November 25). Perl array splice() function - Quick Tutorial. Retrieved from https://www.thoughtco.com/perl-array-splice-function-quick-tutorial-2641163 Brown, Kirk. "Perl array splice() function - Quick Tutorial." ThoughtCo. https://www.thoughtco.com/perl-array-splice-function-quick-tutorial-2641163 (accessed September 24, 2017).