Stack in
Perl is a linear data structure that follows the
LIFO (Last In First Out) or
FILO (First In Last Out) order.
In simpler terms, a stack is an array in which insertion and deletion takes place at only one end called the top of the stack.
Pushing is the process of insertion of elements into a stack.
Popping is the process of removal of topmost element of a stack.
Making a stack
Creating a stack in Perl is rather simple. All we need to do is declare an array.
The stack could be empty, as follows:
@stack;
Or it could be initialized:
@stack = (1, 2, 3);
Pushing items to a stack
Pushing can be done using either the
push() function or the
splice() function.
-
Pushing using push():
Syntax: push(@stack, list);
Parameters:
- @stack - The stack on which push is to be performed.
- list - The elements to be pushed into a stack. These elements might be scalar, array, hash or any combination of these.
Example:
Output:
Original Stack: 1 2 3
Updated Stack: 1 2 3 scalar a r r a y Geeks 10 for Geeks 20
-
Pushing using splice():
Syntax: splice(@stack, scalar(@stack), 0, list);
Parameters:
- splice() function appends the 'list' at the end of @stack.
- THe 'list' could be a scalar, an array or a hash.
Example:
Output:
Original Stack: 1 2 3
Updated Stack: 1 2 3 scalar a r r a y Geeks 10 for Geeks 20
Popping elements from a Stack
Popping can be done using either the pop() function or the splice() function.
-
Popping using pop():
Syntax: $popped_element = pop(@stack);
Parameters:
- pop() function returns the popped element.
- $popped_element contains the element popped from the stack.
Example:
Output:
Original Stack: 1 2 3
Popped element: 3
Updated Stack: 1 2
- If the stack is empty, undef is returned. undef is analogous to NULL in Java and None in Python. However, no error is raised.
Example:
-
Popping using splice()::
Syntax: $popped_element=splice(@stack, -1);
Parameters:
- splice() function removes the last element of the stack and returns it.
- $popped_element stores the returned value.
Example:
Output:
Original Stack: 1 2 3
Popped element: 3
Updated Stack: 1 2
- An error is raised, if the stack is empty. The following code raises an error:
Runtime Error:
Useless use of a variable in void context at /home/59c7c19979aa9e46564cd145d5fe5601.pl line 6.
Modification of non-creatable array value attempted, subscript -1 at /home/59c7c19979aa9e46564cd145d5fe5601.pl line 10.