Perl | Implementing a Queue
Last Updated :
12 Jul, 2025
Prerequisite: Stack
Queue in Perl is a linear abstract data structure which follows the FIFO (First In First Out) order. It resembles the properties of the queue which we encounter in our daily life where the person who comes first will be served first. It is open at both ends. Unlike stack where the operation of insertion and deletion occurs at same end called the top of stack, in queue these operations occur at different ends called the front and rear end of the queue.
Operations on Queue:
The following basic operations are performed on a queue:
- Enqueue (Insertion): Adds an item to the queue. An Overflow condition occurs if the queue is full.
- Dequeue (deletion): Removes an item from the queue. An Underflow condition occurs if the queue is empty.
- Front: Get the front item from queue.
- Rear: Get the last item from queue.

Creating a Queue
Creating a queue in Perl is very simple. It can be done by declaring an array which can be either empty or initialized with some pre-filled data.
@queue; # Queue is empty.
@queue = (1, 2, 3); # Queue with initialized values.
Types of Queues
Based on the criterion of Insertion and deletion, queues can be of the following types:
Simple Queue
Simple Queue is simply a queue where insertion takes place at front and deletion takes place at end of the queue.
In Perl, the operations of a queue can be implemented using push and shift functions.
The push function is used to add one or more values at the end of the queue.
The shift function will move the queue one unit to the left deleting (popping) the first element. It will return undef in case of empty queue.
Examples:
Perl
#!/usr/bin/perl
use strict;
use warnings;
# Intitialising the Queue
my @queue = (1, 2, 3);
# Original queue
print "Original Queue: @queue";
# Pushing values into queue
push(@queue, (4, 5, 6));
# Updated Queue after
# Push operation
print("\nUpdated Queue after Push: @queue");
# Popping values from queue
my $val1 = shift(@queue);
print("\nElement popped is: $val1");
my $val2 = shift(@queue);
print("\nElement popped is: $val2");
# Updated Queue after
# Pop operations
print("\nUpdated Queue after Pop: @queue");
Output: Original Queue: 1 2 3
Updated Queue after Push: 1 2 3 4 5 6
Element popped is: 1
Element popped is: 2
Updated Queue after Pop: 3 4 5 6
Circular Queue
In circular queue, the last position of the queue is connected to the first position to make a circle, also called as Ring Buffer. If the queue is empty from front side but full at the end, then also we can insert elements in the circular queue, which is not the case in the simple queue. The circular queue will be of fixed size, unlike a normal queue.
In additions to push and shift functions, circular queue also has two variables front and rear to store the front and the rear positions of the queue.
Example:
Perl
#!/usr/bin/perl
use strict;
use warnings;
# Intitialising the Queue
my @queue = (1, 2, 3);
my $size = 7; # No. of elements to be stored in queue
# Initially queue has three elements
my $front = 0;
my $rear = 2;
# Original queue
print "Original Queue: @queue";
# Pushing values into queue
$rear = ($rear + 1) % $size;
my $val = 4;
while(1)
{
if ($rear == $front)
{
print("\nQueue is full.");
last;
}
else
{
print("\nPushed $val in queue");
$queue[$rear] = $val;
$rear = ($rear + 1) % $size;
$val += 1;
}
}
# Updated Queue after
# Push operation
print("\nUpdated Queue after Push: @queue");
# Popping values from queue
my $val1 = $queue[$front];
$queue[$front] = -1;
$front = ($front + 1) % $size;
print("\nElement popped is: $val1");
my $val2 = $queue[$front];
$queue[$front] = -1;
$front = ($front + 1) % $size;
print("\nElement popped is: $val2");
# Updated Queue after
# Pop operations
print("\nUpdated Queue after Pop: @queue");
while(1)
{
if ($rear % $size == $front)
{
print("\nQueue is full.");
last;
}
else
{
print("\nPushed $val in queue");
$queue[$rear] = $val;
$rear += 1;
$val += 1;
}
}
print("\nUpdated Queue after Push: @queue");
Output: Original Queue: 1 2 3
Pushed 4 in queue
Pushed 5 in queue
Pushed 6 in queue
Pushed 7 in queue
Queue is full.
Updated Queue after Push: 1 2 3 4 5 6 7
Element popped is: 1
Element popped is: 2
Updated Queue after Pop: -1 -1 3 4 5 6 7
Pushed 8 in queue
Pushed 9 in queue
Queue is full.
Updated Queue after Push: 8 9 3 4 5 6 7
Priority Queue
In priority queue, every item has a defined priority associated with it. An item having the least priority will be the first to be removed from the priority queue. The items with same priority will be dealt with in the order of their
position in the queue.
Examples:
Perl
#!/usr/bin/perl
use strict;
use warnings;
# Initialising queue with priority
my @queue = ([1, 3], [2, 7], [4, 3], [5, 2]);
sub pull_highest_prio
{
my $max = 0;
for (my $i = 0; $i < scalar(@queue); $i++)
{
if ($queue[$i][1] > $queue[$max][1])
{
$max = $i;
}
}
print("\nPopped item: $queue[$max][0], ",
"Priority: $queue[$max][1]");
splice @queue, $max, 1;
}
# Driver Code
print("\nOriginal Queue is ");
for (my $i = 0; $i < 4; $i++)
{
print("$queue[$i][0] ");
}
push(@queue, [11, 9]);
push(@queue, [7, 0]);
print("\nUpdated Queue after push is ");
for (my $i = 0; $i < 6; $i++)
{
print("$queue[$i][0] ");
}
pull_highest_prio;
pull_highest_prio;
pull_highest_prio;
pull_highest_prio;
print("\nUpdated Queue after pop is ");
for (my $i = 0; $i < 2; $i++)
{
print("$queue[$i][0] ");
}
Output: Original Queue is 1 2 4 5
Updated Queue after push is 1 2 4 5 11 7
Popped item: 11, Priority: 9
Popped item: 2, Priority: 7
Popped item: 1, Priority: 3
Popped item: 4, Priority: 3
Updated Queue after pop is 5 7
Deque(Doubly Ended Queue)
Doubly Ended Queue is just a generalized version of simple queue, except the insertion and deletion operations, can be done at both Front and Rear end of the queue. It is a very important type of data structure as it can be used both as a stack or a queue.
Examples:
Perl
#!/usr/bin/perl
use strict;
use warnings;
# Intitialising the Queue
my @queue = (1, 2, 3);
my $front = 0;
my $rear = 2;
sub insert_front
{
my $val = $_[0];
unshift(@queue, $val);
$rear += 1;
}
sub insert_rear
{
my $val = $_[0];
push(@queue, $val);
$rear += 1;
}
sub delete_front
{
print("\nElement popped is: $queue[0]");
splice @queue, 0, 1;
$rear -= 1;
}
sub delete_rear
{
print("\nElement popped is: $queue[$rear]");
splice @queue, scalar(@queue) - 1, 1;
$rear -= 1;
}
# Original queue
print "Original Queue: @queue";
# Pushing values into queue
&insert_rear(4);
&insert_rear(3);
print("\nRear element is $queue[$rear]");
&insert_front(1);
&insert_front(7);
print("\nFront element is $queue[$front]");
# Updated Queue after
# Push operation
print("\nUpdated Queue after Push: @queue");
# Popping values from queue
delete_rear;
delete_front;
print("\nFront element is $queue[$front]");
&insert_front(20);
delete_rear;
print("\nRear element is $queue[$rear]");
# Updated Queue after
# Pop operations
print("\nUpdated Queue after Pop: @queue");
Output: Original Queue: 1 2 3
Rear element is 3
Front element is 7
Updated Queue after Push: 7 1 1 2 3 4 3
Element popped is: 3
Element popped is: 7
Front element is 1
Element popped is: 4
Rear element is 3
Updated Queue after Pop: 20 1 1 2 3
Abstract Implementation
Abstract means to hide the functionality of the operations from the normal user, that is to provide the operational functionality without defining the logic behind the function.
In Perl, the abstract implementation of queue can be achieved using Perl's in-built module Thread::Queue which provide thread-safe FIFO queues that can be accessed by any number of threads.
Basic methods:
- new(list) - Creates a new queue with the provided list of items or if not listed it creates a new empty queue.
- enqueue(list) - Adds a list of items onto the end of the queue.
- dequeue(COUNT) - Removes the requested number of items from the head of the queue, and returns them and if not mentioned it dequeues one element from the queue.
- pending() - Returns the number of items still left in the queue or we can say, it basically returns the size of the queue.
- end() - declares that no more items will be added to the queue.
Examples:
Perl
#!/usr/bin/perl
use strict;
use warnings;
use Thread::Queue;
# A new pre-populated queue
my $q = Thread::Queue->new(1, 2, 3);
sub head
{
if ($q->pending() == 0)
{
print("\nThe queue is empty.");
}
else
{
my $item = $q->dequeue();
print("\nHead of the Queue is $item.");
}
}
my $isize = $q->pending();
print("Initial size of the queue is $isize");
# insert three items at the back of the queue
$q->enqueue(5, 6, 7);
&head();
my $size = $q->pending();
print("\nThe size of the queue is $size");
# delete the head item of the queue
$q->dequeue();
&head();
# delete two items from the front
$q->dequeue(2);
my $size2 = $q->pending();
print"\nThe size of the queue is $size2";
&head();
&head();
$q->end();
Output: size of the queue is 3
Head of the Queue is 1.
The size of the queue is 5
Head of the Queue is 3.
The size of the queue is 1
Head of the Queue is 7.
The queue is empty.
Parallel or Asynchronous Processing
The word Parallel means simultaneously or at the same time and Asynchronous refers to continuous or non-blocking. The implementation operations of a queue are blocking i.e while performing one operation the other operation have to wait for it to end first and are then executed. This is fine for small number of tasks but for a large number of tasks or operations, this type of processing is a bit hectic and time-consuming.
To overcome this problem, Perl provide some way of doing parallel or asynchronous processing so that these operations can run simultaneously or without waiting for other to end. The two major solutions for this is threading and forking. Forking is to create exactly same copy of some process and then these two processes executes in parallel without much connection between their variables, although they manipulate or work upon same variables(copy). It is done using fork() function.
Examples:
Perl
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
say "PID $$";
my $pid = fork();
die if not defined $pid;
say "PID $$ ($pid)";
Output: PID 22112
PID 22112 (22113)
PID 22113 (0)
Before calling fork(), we got a PID (22112) which is the process ID for current process, after forking we got two lines. The first printed line came from the same process as the current (it has the same PID), the second printed line came from the child process (with PID 63779). The first one received a $pid from fork containing the number of the child process. The second, the child process got the number 0.
Perl also supports event-driven programming through POE framework.
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