PERL Interview Questions and Answers

Perl is a high-level, general-purpose, dynamic programming language that supports Procedure Oriented Programming (POP) and Object-Oriented Programming (OOP) paradigms. Like other high-level languages, it also supports data types, strings, arrays, etc., to develop real-world applications. Whether you are preparing for a beginner or advanced-level interview, you will become more confident with our set of Perl interview questions and answers. The questions are divided into various sections like date and time handling, arrays, modules and packages, regular expressions, and OOPs. By using Perl Interview Questions, you can confidently ensure that you are adequately equipped for your upcoming interview.

  • 4.5 Rating
  • 50 Question(s)
  • 50 Mins of Read
  • 4167 Reader(s)

Beginner

Two applications developed using Perl programming are Gedit (for Linux) and Notepad++ (for Windows).

Expect to come across this popular question in Perl basic interview questions.

Perl is a high-level, interpreted, general-purpose programming language created by Larry Wall. Initially, the language was called "Practical Extraction and Reporting Language", and this was later made into the acronym – Perl. This language borrows its features from other languages, including C, Shell Script (sh), and AWK. It was initially developed as general-purpose programming language for text manipulation. Nowadays, developers use it for web application development, network programming, system administration tool development, GUI app development, and more.

Perl is a general-purpose, high-level programming language. The term general-purpose means developers can use this language in web development, text processing, desktop application development, network programming, etc. Apart from all these, there are several other advantages of Perl programming. These are:

  • It is easy to learn due to its simple syntax.
  • This programming language supports multiple platforms.
  • It is simple to use because of its flexibility.
  • It comes with an advanced framework that makes Perl development very efficient.
  • It is open-source, and hence easy to use.
  • It supports Object-oriented programming.
  • Programmers can easily read its code and understand it.

Every good thing comes with some drawbacks. Some disadvantages of Perl programming are: 

  • Until you become professional in programming and smooth with Perl, debugging and fixing bugs is difficult in Perl. 
  • It has a tremendous maintenance requirement, as developers need someone who can dedicatedly work to make sure the Perl-based application runs smoothly. 
  • It comes with a lot of mathematical symbols that developers need to master. It takes too much time. 
  • Perl is not the best choice for beginners who want to learn to program. 
  • Perl supports only front-end application development. 

As we all know, Perl is an object-oriented programming language, so it supports the concept of inheritance. Inheritance is the concept that helps Perl programmers leverage code reusability. Inheritance simply means that methods, properties, and data members of a base/parent class will remain available and accessible to the derived/child classes. So, programmers do not have to write the same code logic repeatedly and simply inherit the properties and methods of the parent class.  

It's no surprise that this one pops up often in Perl interview questions and answers.

Yes, Perl supports the concept of objects. But it is not compulsory to use objects. Perl allows using various object-oriented concepts without using or understanding the objects. But in case the developer is creating a heavy application and the program is too large, then it is suitable for the programmer to make it object-oriented.

Yes. Like other programming languages like C, C++, Java, C#, Python, etc., Perl is a case-sensitive programming language.

The acronym CPAN stands for Comprehensive Perl Archive Network. It is a Perl repository that contains 250,000 Perl software development modules. Also, all of these come with accompanying documentation for 39,000 distributions, with around 12,000 contributors. Most of the CPAN modules are free and open source. It acts as an archive network or the Perl program or as a Package manager for the automated software installer.  

The say() function in Perl is like the print() function which displays any string or variable passed within it as arguments. The only difference between say() and print() is that it automatically appends a new line at the end of every output string.

In Perl, hashes are a collection of key-value pairs having unordered forms. In this collection, the keys are unique strings, and their corresponding values are scalar elements. Hashes are preceded with a percent (%) sign. They get indexed and accessed through their key values. 

Scalars are variables that can contain only a single unit of data at a time. That data is said to remain stored in scalar variables. Perl supports different types of scalar values. These are character, string, numbers, floating-point values, references, etc. The $ (dollar) sign is used to create scalars.  

Arrays in Perl contain an ordered list of scalar values. It has a preceding at (@) sign. For accessing a single element from within the Perl array, developers use the dollar ($) sign. The syntax for declaring arrays in Perl is: 

@array_Name = (1stElement, 2ndElement, 3rdElement.... nthElement); 

Yes, Perl programmers can load binary extensions dynamically. But, for that, your system should support more functionality than what is currently available, so it can load it up and keeps running. But then, if the binary extension does not recommend it, programmers have to calculate & compile the extension manually.

One of the most frequently posed Perl interview questions for experienced, be ready for it.  

Perl array contains a set of specific functions associated with the Perl array. These functions help in adding or removing elements to or from an array. There are four different types of Perl array functions. These are: 

  • Push: Pushes one element in the array 
  • Pop: Pulls out one element from the array 
  • Shift: Returns the first value in an array, removing it and shifting the elements of the array list to the left by one. 
  • Unshift: Places the given list of elements at the beginning of an array by shifting all the values in the array by right. 

The void context is a type of context that does not care about the return value is. Also, it does not demand a return value when applied within the program. 

The merged array function in Perl helps in merging two arrays into a single array. It eliminates all the commas residing in between them. 

@arrayOne = ("Gaurav", "Karlos", "Ray", "is", "here");   
@arrayTwo = ("He", "wrote", "this");   
# merge operation performed on both the above given arrays 
@merged = (@arrayOne, @arrayTwo);   
print "@merged \n"; 

Programmers use the delete function to remove a hash element from the hash group. It eliminates both keys and their respective value elements from the hash. The syntax of the delete function is: 

delete($hash_name{key_name}); 

Subroutines in Perl are named blocks containing a set of instructions meant for a specific operation. They accept arguments and can return values operated within themselves. Perl programmers can divide their code into meaningful sub-units.  

The syntax is: 

sub subroutine_name { 
   body of the subroutine 
} 
Program: 
# Function definition 
sub Hey { 
   print "Hey, Karlos ! \n"; 
} 
# Function call 
Hey(); 

When a programmer creates a variable with the help of the 'my' operator and it is private in nature, they are called the lexical variables. It stays alive from the spot it got declared till the end, where the block (pair of curly braces) finishes. 

Example: 

my $g; 
my @k; 
my %r;

The conditional statement in Perl helps in making decisions. Based on that decision, a valid Perl statement or set of instructions gets executed. Through conditional statements, a programmer checks a condition or set of conditions. Perl caters to 7 different types of conditional statements. These are: 

  • if statement 
  • if-else statement 
  • If-elsif statement 
  • unless statement 
  • unless else statement 
  • unless...elsif..else 
  • switch 

The syntax of if else statement in Perl is: 

if(boolean_expression) { 
   # statement(s) will execute if the given condition is true 
} else { 
   # statement(s) will execute if the given condition is false 
} 

A loop statement allows a programmer to perform a repetitive task or execute a set of statements multiple times in iterations. It is essential when programmers need to execute a block of code several times. Iterative statements get executed sequentially. There are specific ways to change the value so that at every iteration, it can show different values. There are five different types of iterative statements in Perl. These are: 

  • while loop 
  • until loop 
  • for loop 
  • foreach loop 
  • do-while loop 

There are two different functions Perl developers can use to include a Perl module. 

  • Use: The method helps in including only the Perl modules (only for including a .pm type file). The included objects get verified during compilation. We do not have to specify the file extension while performing the import with the use function. The loading of the module is done at compile time. 

The syntax is: 

 use Module_name; 

In case you have a module file as “math.pm”, the code will be: 

use math; 
  • Require:  The method helps in including libraries and modules. The included objects get verified during runtime. When using the required function, we have to specify the file extension of the module. Also, the loading of the module is carried out at runtime. The syntax is: 

require modulename.extension; 

In case you have a module file as “math.pm”, the code will be: 

require math.pm; 

There are various benefits that Perl caters to its developers and stays ahead of other programming languages. The situations are: 

  • When a developer needs faster execution through their application, Perl will provide you solution for that demand.  
  • Perl is comfortable with other web scripting languages like HTML and CSS. 
  • Perl also caters to a lot of flexibilities when developing web-based applications. 
  • Applications that require frequent use of regular expressions and text manipulation can render Perl for their development purpose. 

Apart from all these situations, Perl is free, plus it has a repository of pre-written codes with community support called CPAN (Comprehensive Perl Archive Network). The Comprehensive Perl Archive Network (CPAN) is a repository of over 250,000 software modules. Some of these are: 

  • DBI 
  • JSON 
  • LWP::UserAgent 
  • DateTime 
  • XML::Simple 
  • Text::CSV 
  • Spreadsheet::WriteExcel 
  • DBD::mysql 
  • XML::Parser 
  • WWW::Mechanize 
  • Excel::Writer::XLSX 
  • Net::SSH::Perl 
  • Net::SMTP 
  • Net::Telnet 
  • DBD::Oracle 
  • Spreadsheet::ParseExcel 
  • IO::Socket::SSL 
  • HTTP::Response 
  • DBIx::Class::ResultSet 
  • Log::Log4perl 

Variables declared using the 'my' keyword reside only within that block scope in which they get declared. Such variables do not get inherited, and the functions do not get visibility when called in that block. Again, when the variables defined as 'local' remain visible in that block. They have visibility in functions when called from that particular block.

In Perl, both Terms and lists have the highest precedence. Terms include expressions in parenthesis, variables, etc. List operators also render the same level of precedence as that of terms. Both these operators have strong left word precedence. 

The entire list of operator precedence in Perl looks like: 

->
left
++ --
nonassoc
**
right
! ~ \ and unary + and -
right
=~ !~
left
* / % x
left
+ - .
left
<< >>
left
< > <= >= lt gt le ge
nonassoc
== != <=> eq ne cmp
nonassoc
&
left
| ^
left
&&
left
||
left
..
nonassoc
?:
right
= += -= *= etc.
right
, =>
left
not
right
and
left
or xor
left

Perl is a feature-rich programming language that can easily handle dates and times within the program. Perl provides a predefined module called the DateTime module. This DateTime is a class that helps in representing various combinations of dates and times. The DateTime module in Perl renders the New Style of the calendar by extending backward in time before its creation (in 1582). This is usually called the “proleptic Gregorian calendar”. In such a calendar, the first day of the calendar (which is also called the epoch) is the first day of year 1 and is believed to be the birth of Jesus Christ. 

The syntax is: use DateTime; 

Program: 

$datetime = localtime();   
print "Local Time of the System : $datetime\n"; 

Perl's goto statement is a jumping statement, that makes a jump from one part of the program to the other when the program encounters the goto label. It is sometimes referred to as the unconditional jump statement because the jumping from one section of the program to the other takes place without any condition. Programmers can use the goto statement anywhere within a function. 

The syntax is:  

LABEL_NAME: 
Statement 1; 
Statement 2; 
. 
. 
. 
. 
. 
Statement n; 
goto LABEL_NAME; 
 
Program: 
sub dispNumb()  
 
    my $numb = 1;  
lab:  
    print "$numb ";  
    $numb++;  
    if ($numb <= 20)  
    { 
        goto lab; 
    } 
 
     
# Driver Code 
dispNumb(); 

Escape sequences are special characters that do not represent themselves when used as a part of string or character literal. All these characters are preceded by a backslash.  

For example: ‘\n’, ‘\t’, ‘\\’, etc. 

Program: 

$result = "This is Mr. \" Karlos \""; 
print "$result \t"; 
print "\$result \n";

The redo statement in Perl restarts the existing loop without evaluating the control statement. Also, further statements within the block won't get executed. 

Program: 

$numb = 10;   
while($numb < 150){   
   if( $numb == 50 ){   
     $numb = $a + 10;   
      redo;   
   }   
   print "Number = $numb \n";   
} continue {   
   $numb = $numb * 2;   
} 

Advanced

A reference in Perl is a scalar data type, which can hold the location of another value that might be arrays, scalar, or Perl hashes. Since references are scalar in nature, programmers can use them anywhere in replacement of a scalar. For creating a reference of any variable, subroutine, or value, we can prefix it with a backslash. 

$hashref   = \%ENV; 
$arrayref  = \@ARGV; 
$scalarref = \$foo; 
$coderef   = \&handler; 

This is a frequently asked question in Perl scripting interview questions.

Perl is a wonderful language to write simple programs in for various functions. Let’s look at some examples of it:  

 sub DisplayDetails { 
   my (%details) = @_;    
   foreach $i (%details) { 
      print "Item : $i\n"; 
   } 
} 
%details = ('Name' => 'Gaurav', 'age' => 28); 
# Creating a reference to the above function. 
$c_ref = \&DisplayDetails; 
# This is a function call that uses the reference. 
&$c_ref(%details); 

Programmers have to dereference a reference variable using the $, @, or % as the prefix of the reference variable. Aliases in Perl are faster compared to references because they do not require any dereferencing.

The three basic file handles are in Perl are: 

  • STDIN: which represents the standard input, 
  • STDOUT: which represents the standard output, and  
  • STDERR: which represents the standard error devices respectively 

This question is a regular feature in Perl advanced interview questions, be ready to tackle it. Here’s a code snippet to open a file using Perl program: 

open(DATA, "<Filename.txt") or die "Unable to open the file Filename.txt, $! "; 
while(<DATA>) { 
   print "$_"; 
} 
< or r: For read only Access 
> or w: For creating, Writing, and Truncating files 
>> or a: For writing, appending, and creating files 
+< or r+: For reading and writing files 
+> or w+: For reading, writing, creating, and truncating files 
+>> or a+: For reading, writing, appending, and creating files 

We can define the context of a subroutine as the type of return value expected by the subroutine. Programmers can use one single function which can return different values. 
Example: 

sub printWriterName { 
   print "Hello Gaurav! \n"; 
} 
   
# calling the subroutine 
printWriterName(); 

We all use different operating systems for our day-to-day tasks. Each of these operating systems come with their own set of commands to look at the files list within a directory. For example, all Linux users use the 'li' command, whereas all Windows users use the 'dir' command to explore the list of directories and sub-directories in their respective OS. Perl provides a universal way of accessing directories in Perl using Perl directory functions. Directory handling in Perl is similar to file handling. Here is a code snippet showing how to access a directory: 

my $directory1 = '/users/karlosray';   
opendir (DIR, $directory1) or die "Unable to open the directory, $!";   
while ($file = readdir DIR) {   
  print "$file \n";   
}   
closedir DIR; 

In this case the file does not exist and hence showed this output. 

For creating a new directory in Perl, we can use the function 'mkdir'. Programmers need to take the required permission for creating a directory. The syntax for the function is: mkdir(directoryName) or die;

It's no surprise that this one pops up often in Perl technical interview questions.

Error handling is the approach of taking appropriate actions against the program when it pops up with an error or is experiencing difficulty in executing the code. There are two types of errors in Perl: 

  • Compile Time Error: In this type of error, usually, programmers make mistakes with the syntaxes or miss file reference that deters the program from a successful compilation. 
  • Run Time Error: In this type of error, the program runs and then encounters an error at the time of running. Such errors are usually logical errors that get produced due to incorrect output or illogical input. 

Perl provides two built-in functions for generating fatal exceptions & warnings. These are: 

die() 
warn() 

In Perl, the die will print a message to the ‘stderr’ before terminating the program. The exit will only terminate the program without showing anything. The 'die' in Perl is catchable using eval, whereas the 'exit' simply quits from the process. 

print "Enter your rate:"; 
$rate = <STDIN>; 
if ($rate < 2000) 
{ 
    exit $rate; 
} 
   
else 
{ 
    print "\n Thanks for the investment! "; 
} 

use strict;   
use warnings;   
open(my $fh, '>', 'sssit/gauravkarlos/perlcode.txt') or die;   
print $fh "An example of error handling using die \n";   
close $fh;

The warn function enables the programmer to raise a warning message that gets printed to STDERR but does not take further action. It is very useful when Perl programmers want to print a warning message for the user plus proceed with the remaining operations −

chdir('/home') or warn "Unable to change to this directory ";

There are specific types of variables whose meanings are predefined and have special significance. They perform a specific function as and when required by the programmer. Most of these Perl special variables come with a long English-like naming convention. For example, Operating System Error variable $! which can be written as: $OS_ERROR. All the special variables available within Perl leverage punctuation characters following the usual variable indicator such as at (@), dollar ($), or percent (%) sign, like $_. 

For example:  

foreach ('Karlos', 'Sue', 'Dee') 
{ 
   print($_); 
   print(" \n "); 
} 

Expect to come across this popular question in Perl coding questions.

The syntax of the for loop in Perl is  

for(initialization; conditional expression; increment or decrement) {   
// code body that needs to be executed repetedly   
} 

But imagine a situation where you have put double semicolon (;;) within the for loop. It means there is no beginning value or terminating condition and hence it will execute for infinite times. To stop executing such infinitely running loops, you can programmers can use the Ctrl + C shortcut. 

Regular expressions are a specially encoded sequence of characters that helps programmers in defining a search pattern within the strings. They began to appear in the mid-1940s for describing regular languages. But gradually by the 1970s, they began to pop up in the programming world for searching and pattern-matching. There are numerous applications of regular expressions. Some practical day-to-day aspects are in data science, data extraction, data pre-processing, pattern matching, natural language processing (NLP), web scraping, etc. 

e.g.: 

$s = "Gaurav Roy"; 
if ($s =~ m[Gaurav])  
{ 
    print "Match Found\n"; 
} 
else  
{ 
    print "Match Not Found\n"; 
} 

Perl supports three different regular expression operators. These are: 

  1. Matching Regular Expression (done through m//) 
  2. Substituted Regular Expression (done through s///) 
  3. Transliterated Regular Expression (done through tr///) 

Here’s the program to search my name from a string through regular expression. 

$strr = "My name is Gaurav and I'm here for a Perl interview"; 
if ($strr =~ /Gaurav/) { 
   print " Your name is there in the string \n"; 
} else { 
   print " Your name is not there in the string \n"; 
} 

A Perl object is simply a reference of the data type that performs various operations on behalf of that class. Perl stores the class object as a reference in a scalar variable. As we know, scalars can hold a reference to the object; programmers can use the same scalar to have different class objects.

Programmers use both base class and derived class concepts while implementing inheritance. The base class is the parent class or super class in which various implementations reside. It helps in the creation of other classes called the derived class.  
The derived class is the child class or the sub class, which gets inherited from the parent class taking some or all its properties. It helps in code reusability.

The next statement is the same as that of the continue statement of C. It helps to skip the elements and move on to the next element of a sequence. 

@array = (a..z);   
print("@array \n");   
for ($i = 0; $i < @array; $i++) {   
    if ($i == 0 || $i == 4 || $i == 8 || $i == 14 || $i == 20) {   
        next;   
    }   
    $array[$i] = "^";   
}   
print("@array\n"); 

As Perl programmers declare variables in their program, they take some memory. It is up to the programmer to make sure that the program is utilizing memory in the best possible way. Programmers take care of memory leakage for efficient programming. Perl has an excellent garbage collector but with an exception. If a programmer uses global variables at all times, rather than local variables (where the garbage collector takes care of these variables as they go out of scope), they will end up using lots of extra memory space. It is because the garbage collector will not remove the unused storage and hence the memory locations will remain occupied unless the computer restarts.

Description

The demand for a general-purpose programming language is immense in the software development market. Developing network protocols, system administration programs, and financial apps are common in the market and for every growing software development business. That is why Perl programmers have great value and reputation in the software development industry. Get certified in web design and elevate your career with our comprehensive web design certification program.

Perl is an interpreted, high-level, open-source, dynamic, stable, general-purpose programming language. Larry Wall developed Perl in 1987 as a general-purpose Unix scripting language to simplify report processing. It provides programmers the ability to perform Procedure Oriented Programming (POP) and Object-Oriented Programming (OOP). Like other high-level languages, it also supports data types, strings, arrays, etc., to develop real-world applications and uses similar constructs and syntaxes as that of C.

Perl also renders a lot of integration like Sentry, Rollbar, Cloudinary, IBM DB2, NGINX, etc., making software development easier for companies. Apart from integrations, it also provides a lot of libraries that make software development fast yet efficient. The average salary of a Perl programmer is 9 lacs per annum. Companies like Genpact, Just Dial, Tech Mahindra, Tata Consultancy Service, CGI, Glow Tech Technologies, Amazon, DuckDuckGo, and Booking.com uses Perl. Learn more about advanced programming online courses through our expert-curated courses. 

Read More
Levels