Perl | splice() - The Versatile Function
Last Updated :
11 Jul, 2025
In
Perl, the splice() function is used to remove and return a certain number of elements from an array. A list of elements can be inserted in place of the removed elements.
Syntax: splice(@array, offset, length, replacement_list)
Parameters:
- @array - The array in consideration.
- offset - Offset of removal of elements.
- length - Number of elements to be removed starting at offset(including offset).
- replacement_list- The list of elements that takes the place of the removed elements.
Example:
perl
#!/usr/bin/perl
# an array of numbers from 0 to 7
@array = (0..7);
# Original array
print "Original Array: @array\n";
# splice() replaces elements from
# 2 to 4 with a to c
@array2 = splice(@array, 2, 3, (a..c));
# Printing the Updated Array
print("Elements of Updated \@array are @array\n");
# array2 contains elements removed
# from array i.e. 2, 3 and 4
print("Removed elements are @array2");
Output:
Original Array: 0 1 2 3 4 5 6 7
Elements of Updated @array are 0 1 a b c 5 6 7
Removed elements are 2 3 4
Cases with multiple parameters:
Case 1: splice(@array)
If the @array is passed but the rest of the parameters are not, the entire array is cleared and all elements returned. However, no error is raised.
Example:
perl
#!/usr/bin/perl
# an array of numbers from 0 to 7
@array = (0..7);
# Original Array
print "Original Array: @array\n";
# All the elements of @array are removed
@array2 = splice(@array);
print("Updated Array: @array\n");#Blank Line
# Removed elements
print("Removed elements are: @array2");
Output:
Original Array: 0 1 2 3 4 5 6 7
Updated Array:
Removed elements are: 0 1 2 3 4 5 6 7
Case 2: splice(@array, offset)
If the @array and offset are passed without specifying length and replacement_list, all the elements from the offset to the end are removed and returned.
Example:
perl
#!/usr/bin/perl
# an array of numbers from 0 to 7
@array = (0..7);
# Original Array
print "Original Array: @array\n";
# All the elements of @array starting
# from @array[3] are removed
@array2 = splice(@array, 3);
print("Updated Array: @array\n");
# Removed elements
print("Removed elements are: @array2");
Output:
Original Array: 0 1 2 3 4 5 6 7
Updated Array: 0 1 2
Removed elements are: 3 4 5 6 7
Case 3: splice(@array, offset, length)
If the @array, the offset, and the length is specified, 'length' number of elements starting from offset are removed.
Example:
perl
#!/usr/bin/perl
# an array of numbers from 0 to 7
@array = (0..7);
# Original Array
print "Original Array: @array\n";
# Two elements of @array starting from
# @array[3] are removed i.e 3 and 4
@array2 = splice(@array, 3, 2);
print("Updated Array: @array\n");
# Removed elements
print("Removed elements are: @array2");
Output:
Original Array: 0 1 2 3 4 5 6 7
Updated Array: 0 1 2 5 6 7
Removed elements are: 3 4
Case 4: splice(@array, offset, length, replacement_list)
In this case, 'length' number of elements are removed and returned. replacement_list takes their place.
Example:
perl
#!/usr/bin/perl
# an array of numbers from 0 to 7
@array = (0..7);
# Original Array
print "Original Array: @array\n";
# Two elements of @array starting from
# @array[3] are removed i.e 3 and 4 and
# replaced by a list of elements i.e. (a, b)
@array2 = splice(@array, 3, 2, (a, b));
print("Updated Array: @array\n");
# Removed elements
print("Removed elements are: @array2");
Output:
Original Array: 0 1 2 3 4 5 6 7
Updated Array: 0 1 2 a b 5 6 7
Removed elements are: 3 4
Note:
- If no array is passed to splice(), an error is raised.
- The number of elements of replacement list need not be equal to the number of removed elements.
Example:
perl
#!/usr/bin/perl
# an array of numbers from 0 to 7
@array = (0..7);
# Original Array
print "Original Array: @array\n";
# Two elements of @array starting from
# @array[3] are removed i.e 3 and 4 and
# replaced by four elements i.e. (a..d)
@array2 = splice(@array, 3, 2, (a..d));
print("Updated Array: @array\n");
# Removed elements
print("Removed elements are: @array2");
Output:
Original Array: 0 1 2 3 4 5 6 7
Updated Array: 0 1 2 a b c d 5 6 7
Removed elements are: 3 4
- The length and the offset can be negative.
Example:
perl
#!/usr/bin/perl
# Two arrays of numbers from 0 to 7
@arr = (0..7);
@arr1 = (0..7);
# Two elements are removed from the
# 3rd element from the end i.e. 5 and 6
splice(@arr, -3, 2);
# Printing First splice()
print('splice(@arr, -3, 2): '."@arr \n");
# Elements from 3 to 2nd element from
# the end are removed i.e. 3, 4 and 5
splice(@arr1, 3, -2);
# Printing Second splice()
print('splice(@arr1, 3, -2): '."@arr1");
Output:
splice(@arr, -3, 2): 0 1 2 3 4 7
splice(@arr1, 3, -2): 0 1 2 6 7
- If the offset is more than the length of the array, replacement_list is attached at the end of the @array.
Example:
perl
#!/usr/bin/perl
# an array of numbers from 0 to 7
@array = (0..7);
# Original Array
print "Original Array: @array\n";
# offset is greater than the
# length of the array.
splice(@array, 9, 2, (a..d));
print("Updated Array: @array\n");
Output:
Original Array: 0 1 2 3 4 5 6 7
Updated Array: 0 1 2 3 4 5 6 7 a b c d
push using splice()
Inserting an element at the end of an array is termed as Push.
Equivalent of push() using splice():
Syntax: splice(@array, scalar(@array), 0, list)
Parameters:
- @array - The array in consideration.
- scalar(@array)- It is the length of the array.
- 0 - It removes no element.
- list - The list of elements to be pushed at the end of the array.
The 'list' is placed at the end of @array. No elements are removed/deleted.
Example:
perl
#!/usr/bin/perl
# Initializing an array
@array = ('Geeks', 'for', 'Geeks.');
# Original Array
print "Original Array: @array\n";
# push function
splice(@array, scalar(@array), 0, ('Hello', 'There!'));
# Printing the updated Array
print("Updated Array: @array\n");
Output:
Original Array: Geeks for Geeks.
Updated Array: Geeks for Geeks. Hello There!
In the above example,
- Initially, @array has the elements: Geeks, for, Geeks.
- scalar(@array) is the length of the array (OR) number of elements in the array, which is 3.
- Elements starting from @array[3] are to be removed but since @array[3] is not present, no elements will be removed.
- The list ('Hello', 'There!') will be inserted at the end of @array. Now, @array has the elements: Geeks, for, Geeks., Hello, There!
pop using splice()
Pop is used to remove and return the last element of the array
Equivalent of pop() using splice():
Syntax: $pop = splice(@array, -1)
Parameters:
- $pop - The popped element.
- @array - The array in consideration
- -1 - Removal of all the elements starting from the last one.
>> One element is removed starting from the last element of the array and is returned to $pop.
Example:
perl
#!/usr/bin/perl
# Initializing an array
@array = ('Geeks', 'for', 'Geeks.');
# Original array
print "Original Array: @array\n";
# last element is removed and returned
$pop = splice(@array, -1);
# Printing the Updated Array
print("Updated Array: @array\n");
# $pop contains removed element
# from array i.e. last element
print("Removed element is $pop");
Output:
Original Array: Geeks for Geeks.
Updated Array: Geeks for
Removed element is Geeks.
In the above example,
- Initially, @array has the elements: 'Geeks', 'for', 'Geeks.'
- In the splice() function, all elements starting from and including the last element are removed i.e. only the last element is removed and returned to $pop.
- Now, @array has the elements: 'Geeks', 'for'. And, $pop has the element: 'Geeks.'
shift using splice()
To move all the elements in an array to the left by one block and removing and returning the first element is termed as Shift.
Equivalent of shift() using splice():
Syntax: $removed = splice(@array, 0, 1)
Parameters:
- $removed - The popped element i.e. the first one.
- @array - The array in consideration
- 0 - Removal of the elements starts from the first one.
- 1 - One element is to be removed starting from and including the first one i.e. only the first element is removed and returned to $removed
>>One element starting from and including the first element is removed and returned to $removed. All the remaining elements in the array are automatically moved to the left by one index.
>>This is similar to pop() except that the removal takes place at the opposite end.
Example:
perl
#!/usr/bin/perl
# Initializing an array
@array = ('Geeks', 'for', 'Geeks.');
# Original array
print "Original Array: @array\n";
# shift function
$removed = splice(@array, 0, 1);
# Printing the Updated Array
print("Updated Array: @array\n");
# $removed contains removed element
# from array i.e. first element
print("Removed element is $removed");
Output:
Original Array: Geeks for Geeks.
Updated Array: for Geeks.
Removed element is Geeks
In the above example,
- Initially, @array has the elements: 'Geeks', 'for', 'Geeks.'
- In the splice() function, one element is removed from the left end of the array.
- Now, @array has the elements: 'for', 'Geeks.'. And, $pop has the element: 'Geeks.'
unshift using splice()
Inserting a given list/array of elements at the left end of an array is termed as Unshift.
Equivalent of unshift() using splice():
Syntax: splice(@array, 0, 0, insertion_list)
Parameters:
- @array - The array in consideration
- 0 - Insertion takes place at the 0th index i.e beginning of the array.
- 0 - No elements are removed or deleted.
- insertion_list- The elements to be inserted.
>>The elements of insertion_list are inserted at the beginning of the array. All the existing elements of the @array are pushed to the right to accommodate the inserted elements.
Example:
perl
#!/usr/bin/perl
# Initializing an array
@array = ('Geeks', 'for', 'Geeks.');
# Original array
print "Original Array: @array\n";
@insertion_list = ('This', 'is');
# unshift function
splice(@array, 0, 0, @insertion_list);
# Printing the Updated Array
print("Updated Array: @array\n");
Output:
Original Array: Geeks for Geeks.
Updated Array: This is Geeks for Geeks.
In the above example,
- Initially, @array has the elements: 'Geeks', 'for', 'Geeks.'
- In the splice() function, elements of @insertion_list are inserted at the beginning of @array.
- Now, @array has the elements: 'This', 'is', 'Geeks, 'for', 'Geeks.'
Similar Reads
Basics
Perl Programming LanguagePerl is a general purpose, high level interpreted and dynamic programming language. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. Since Perl is a lot similar to other widely used lan
3 min read
Introduction to PerlPerl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is "Practical Extraction and Reporting Language". Some of the programmers also refer Perl as the
9 min read
Perl Installation and Environment Setup in Windows, Linux, and MacOSPrerequisite: Introduction to Perl Before, we start with the process of Installing Perl on our System, whether it be Windows, Linux or Macintosh. We must have first-hand knowledge of What the Perl Language is and what it actually does?. Perl is a general purpose, high level interpreted and dynamic p
3 min read
Perl | Basic Syntax of a Perl ProgramPerl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and
10 min read
Hello World Program in PerlPerl programming language is exclusively designed for text processing purposes. Its abbreviation denotes Practical Extraction and Report Language. It is compatible on various platforms, such as Windows, Mac OS, and almost all versions of UNIX. Hello World! program in every programming language gives
3 min read
Fundamentals
Control Flow
Perl | Decision Making (if, if-else, Nestedâif, if-elsif ladder, unless, unless-else, unless-elsif)Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These
6 min read
Perl | Loops (for, foreach, while, do...while, until, Nested loops)Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the pro
7 min read
Perl | given-when Statementgiven-when statement in Perl is a substitute for long if-statements that compare a variable to several integral values. The given-when statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. given is a c
4 min read
Perl | goto statementThe goto statement in Perl is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function. Syntax: LABEL: Statement 1; Statement 2; . . . . . Statement n; goto LABEL; In the above syntax, the
3 min read
Arrays & Lists
Perl | ArraysIn Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Example: @number = (50, 70, 46); @names = ("Geeks", "For",
6 min read
Perl | Array SlicesIn Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Arrays can store any type of data and that data can be acce
3 min read
Perl | Arrays (push, pop, shift, unshift)Perl provides various inbuilt functions to add and remove the elements in an array. .string-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .string-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padd
3 min read
Perl List and its TypesIntroduction to Lists A list is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to construct a list. In Perl, scalar variables start with a $ symbol wher
4 min read
Hash
Scalars
Strings
Perl | Quoted, Interpolated and Escaped StringsA string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (â) or double quote (â). Quoted Stri
4 min read
Perl | String OperatorsOperators are the foundation of any programming language. Thus, the functionality of Perl programming language is incomplete without the use of operators. A user can define operators as symbols that help to perform specific mathematical and logical computations on operands. String are scalar variabl
4 min read
Perl | String functions (length, lc, uc, index, rindex)String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follow
4 min read
OOP Concepts
Object Oriented Programming (OOPs) in PerlObject-oriented programming: As the name suggests, Object-Oriented Programming or OOPs refers to languages that uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind to
7 min read
Perl | Classes in OOPIn this modern world, where the use of programming has moved to its maximum and has its application in each and every work of our lives, we need to adapt ourselves to such programming paradigms that are directly linked to the real-world examples. There has been a drastic change in the competitivenes
6 min read
Perl | Objects in OOPsPerl is an Objected Oriented, dynamic and interpreter based programming language. In object-oriented programming, we have three main aspects, which are, object, class, and methods. An object is a data type which can be specifically called as an instance of the class to which it belongs. It can be a
6 min read
Perl | Methods in OOPsMethods are used to access and modify the data of an object. These are the entities which are invoked with the use of objects of a class or a package itself. Methods are basically a subroutine in Perl, there is no special identity of a method. Syntax of a method is the same as that of a subroutine.
5 min read
Perl | Constructors and DestructorsConstructors Constructors in Perl subroutines returns an object which is an instance of the class. In Perl, the convention is to name the constructor "new". Unlike many other OOPs, Perl does not provide any special syntax for constructing an object. It uses Data structures(hashes, arrays, scalars) t
4 min read
Perl | Method Overriding in OOPsIn any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signat
6 min read
Perl | Inheritance in OOPsInheritance is a key concept in object-oriented programming that allows you to define a new class based on an existing class. The new class, called a subclass or derived class, inherits all of the properties and methods of the existing class, called the superclass or base class, and can also define
7 min read
Perl | Polymorphism in OOPsPolymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as poly means many and morphism means types. Polymorphism is one of the most important concepts of object-oriented programming languages. The most common use of polymorphism in object
4 min read
Perl | Encapsulation in OOPsEncapsulation in Perl is the process of wrapping up of data to protect it from the outside sources which need not have access to that part of the code. Encapsulation is a part of the Object-oriented programming, it is used to bind the data and the subroutines that are used to manipulate that data. I
6 min read
Regular Expressions
File Handling
Perl | File Handling IntroductionIn Perl, file handling is the process of creating, reading, writing, updating, and deleting files. Perl provides a variety of built-in functions and modules that make it easy to work with files. Here's an introduction to file handling in Perl: File modes:When opening a file in Perl, you need to spec
7 min read
Perl | Opening and Reading a FileA filehandle is an internal Perl structure that associates a physical file with a name. All filehandles have read/write access, so once filehandle is attached to a file reading/writing can be done. However, the mode in which file handle is opened is to be specified while associating a filehandle. Op
4 min read
Perl | Writing to a FileA filehandle is a variable that is used to read and write to a file. This filehandle gets associated with the file. In order to write to the file, it is opened in write mode as shown below: open (FH, â>â, âfilename.txtâ); If the file is existing then it truncates the old content of file with the
3 min read
Perl | Useful File-handling functionsPerl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. These operations can be performed by the use of various inbuilt file functions. Example: Perl #!/usr/bin/perl # Opening a
2 min read