Google News
logo
Perl Interview Questions
* Perl stands for Practical Extraction and Reporting Language. It is a high-level programming language written by Larry Wall, specially designed for processing text. 
 
* Perl 1.0 was released to usenet's alt.comp.sources in 1987
 
* It supports object-oriented programming, and its syntax is quite similar to C language. It is much more flexible to use. Due to its strong text processing abilities, it has become one of the most popular languages for writing Common Gateway Interface(CGI) scripts.
 
* Perl is an Open Source software, licensed under its Artistic License, or the GNU General Public License (GPL).
* Perl supports Unicode.
 
* Perl is Y2K compliant.

*
 Perl works with HTML, XML, and other mark-up languages.

* Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others.
 
* Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others.
 
* Perl supports both procedural and object-oriented programming.
 
* Perl interfaces with external C/C++ libraries through XS or SWIG.
 
* Perl is extensible. There are over 20,000 third party modules available from the Comprehensive Perl Archive Network (CPAN).
 
* The Perl interpreter can be embedded into other systems.
Perl is said to be both compiler and interpreter. It reads the source code, converts the program into bytecode before execution and then runs it. Hence, Perl is sometimes called an interpreter/compiler.
It stands for Comprehensive Perl Archive Network and is a large collection of all the documents and software related to Perl. The programmers can access the same and can avoid the difficulties they face.  CPAN is of significant use for the programmers and they are free to derive a lot of useful information from the same.
Perl advantages :
* It is more flexible to use.
* Its syntax is simple, which makes it easy to understand.
* It supports OOP concepts.
* Perl programs run easily on the system.
* It supports all platforms and is much more portable.
* It has a rich set of Perl modules and free software.
* It is much more efficient to work on text and string manipulation as it is a scripting language.
* Perl combines features of many other languages which make it easy to understand.

Perl disadvantages :
* A Perl program containing CPAN modules will not run on another system which doesn't have CPAN modules installed.
* It is an interpretative language, so it is slower in comparison with other languages.
* It has untidy and unreadable codes.
* It starts creating problems when the code is larger than 200 lines.
* It is not portable.
S.No Perl C
1 There are several development tools in Perl as compare to C Development tools are less and are not very advanced
2 It executes more slowly than C in a few situations C has speed almost equal to that of Perl
3 Code can be hidden in Perl The same is not possible in the case of C
4 The executable can be created without depending on the additional tools Additional tools are the prime requirement 
Scalar : It is denoted by $ symbol. Variable can be a number or a string.
 
Array : Denoted by @ symbol prefix. Arrays are indexed by numbers.
 
The namespace for these types of variables is different. For Example : @add, $add. The scalar variables are in one table of names or namespace and it can hold single specific information at a time and array variables are in another table of names or namespace. Scalar variables can be either a number or a string
$pvt = Calculation(5,5);
print("Result = $pvt\n");
sub Calculation{
my ($fstVar, $secndVar) = @_;
my $square = sub{
return($_[0] ** 2);
};
return(&$square($fstVar) + &$square($secndVar));
};
Output : Result = 50
9 .
Write a program to concatenate the $firststring and $secondstring and result of these strings should be separated by a single space.
Syntax :
 
$result = $firststring . ” “.$secondstring;
 
Program :
#!/usr/bin/perl

$firststring = "abcd";

$secondstring = "efgh";

$combine = "$firststring $secondstring";

print "$Combine\n";
 
Output :
abcd efgh
The scalar : It can hold one specific piece of information at a time (string, integer, or reference). It starts with dollar $ sign followed by the Perl identifier and Perl identifier can contain alphanumeric and underscores. It is not allowed to start with a digit. Arrays are simply a list of scalar variables.
 
Arrays :
 
Arrays begin with @ sign. Example of array :
my @arrayvar = ("string a", "string b "string c");
Associative arrays: It also frequently called hashes, are the third major data type in Perl after scalars and arrays. Hashes are named as such because they work very similarly to a common data structure that programmers use in other languages–hash tables. However, hashes in Perl are actually a direct language supported data type.
Enlisted below are the various Characteristics of Perl :
 
* Case-sensitive
* Easy to code
* Open-source
* Portable and cross-platform.
* Extendable
* No distinction between the types of variables.
* Can return non-linear types likes arrays etc.
* Non-scalars can be used as loop indices.
* Supports high-level intrinsic operations – Example : stack Push/pop.
* Powerful text manipulation API including Regular expressions.
The following arguments can be used while executing a Perl program.
 
w – argument shows a warning.
d – used for debugging.
c – compiles only do not run.
e – execute.

We can also use a combination of arguments like :
pl –wd filename.pl
Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a number, a string, or a reference. A reference is actually an address of a variable, which we will see in the upcoming chapters.
Arrays are ordered lists of scalars that you access with a numeric index which starts with 0. They are preceded by an "at" sign (@).
Hashes are unordered sets of key/value pairs that you access using the keys as subscripts. They are preceded by a percent sign (%).
Perl variables do not have a data type. The data type of a variable in Perl is inferred from its value.
 
A variable in Perl can be defined as follows :
$x = 10;
$base_str = ‘Hello’;
Value needs to be assigned to a variable before using it. Without this, the program may result in an unexpected output.
Variables having values with linear data types like integer, float or string are called scalar variables in Perl.
$x=10;
$mystr=”abc”;
These are all scalar variables.
Numeric operators in Perl are as follows :
 
* Arithmetic operators :  (+,-,*/).

* Comparison operators :
  to compare two numbers (>, <, ==, !=,<=,>=,<=>).

* Bitwise Operators :
(&(and), |(or),^(ex-or),~(not),<<(shift left),>>(shift right)).

Arithmetic operators perform from left to right while Bitwise operators perform an operation from right to left.
Perl supports various string operators as shown below :
 
Equality Operators
Equal eq
Not Equal ne
Comparison cmp
Less than lt
Greater than gt
Less than or equal le
Greater than or equal ge
Well, every programmer is familiar with this approach. The fact is many errors declare their presence in the programs due to reasons which are not always necessary to be known exactly. Eliminating these errors is very essential for the smooth flow of the tasks. Finding bugs or errors is known as debugging. The programming languages can have in-built options for debugging or the programmers are free to consider other options too. 
It is considered when it comes to importing the functions in a way that they can be accessed directly during the program. The users are free to get the results in case the substatements are not accurate. On the other side, the use statement is generally executed during parsing. 
The Perl say() function is not supported by older Perl versions. It is like Perl print() function with only one difference that it automatically adds a new line at the end.
A variable is a place to store values reserving some memory space. Perl treats the same variables differently based on context.
 
There are three types of Perl variables :
 
Scalars ($) : It stores a single value.
 
Arrays (@) : It stores a list of scalar values.
 
Hashes (%) : It stores associative arrays which use a key value as index instead of numerical indexes
Size of an array is determined with scalar context on the array. Array length will always be one greater than its largest index.
 
Perl size = $#arrayName +
 
Where $#arrayName is the maximum index of the array.
There are four types Perl array functions :
 
* Push : The Perl push array function appends a new element at the end of an array.

* Pop : The Perl pop array function removes the last element of an array.

* Shift : The Perl shift array function removes the leftmost element from the array shortening array by 1.

* Unshift : The Perl shift array function adds a new element at the start of an array.
Use : It is used only for the Perl modules. The included modules are verified at the time of compilation. It does not need the file extension.
 
Require : It is used for both Perl modules and libraries. The included objects are verified at runtime. It does need the file extension.
There are three types of loop control statement :
 
* Next : Perl next statement is like continue statement in C. It lets you move on to the next element of your array or hash skipping all elements in between.

* Last : It terminates the loop statement and transfers execution to the statement immediately following the loop. continue statement.

* Redo : Perl redo statement restarts the current loop without evaluation of the control statement.
Perl warnings help us to check errors in our code by giving warnings.
 
To enable them use -w :
perl -w scriptName.pl  
Alternatively, you can also supply it within the "shebang" line :
#/usr/local/bin/perl -w  
The "use strict" command in Perl calls strict pragma. This pragma helps to catch some bugs or errors in our script and stops the program execution.
Strings are an essential part of Perl. They are scalars, so they start with $ sign. Strings can be placed inside single or double quote.
 
Two types of string operators are there :
 
* Concatenation (.)

* Repetition (x)
In the single quote, the value is printed as it is given inside the string without interpolation.
 
In the double quote, the value is printed with interpolation given inside the string.
These are generally the messages that simply let the user keep an eye on the quality of code. With the appropriate messages, it becomes simple for a user to highlight problems. The user can set the messages as optional while working on the programs. 
There is no literal representation in the content of a hash. The users have to make sure that the unwinding of hash before it is actually filled with the data. The value pairs can be created simply and they can then be converted. In the process of conversion, the hashes can be selected randomly.
 
(OR)
 
This hash in this programming language is a group of key values. These are scalar values. The hashes are used after a % sign and can be created only by assigning a value to it.
 
For incorporating information in hashes, the key-value pairs should be created which is known as the unwinding of hash. In this case, the even number items are listed on the right called values, and the ones stored on the left are termed as keys.
Yes, Perl is equipped with some very useful Objects. The best part is programmers are not forced to use them while performing their tasks. The users can easily skip them in case they don’t felt their need while writing the codes. Certain Object-Oriented modules are present in Perl and the users are free to consider them without actually understanding the objects. However, it is recommended to the programmers to go with the Objects in case the program is too complex. 
$test = 2.3456;
{
  my $test = 3;
  print "In block, $test = $test ";
  print "In block, $:: test = $:: test ";
}

  print "Outside the block, $test = $test ";
  print "Outside the block, $:: test = $::test ";

Output :

In block, $test = 3

In block, $::test = 2.3456

Outside the block, $test = 2.3456

Outside the block, $::test = 2.3456

The scope of “my” variable visibility is in the block only but if we declare one variable local then we can access that from the outside of the block also. ‘my’ creates a new variable, ‘local’ temporarily amends the value of a variable.

The command line arguments in Perl are stored in an array @ARGV.
 
$ARGV[0] (the first argument)
 
$ARGV[1] (the second argument) and so on.
 
$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1
37 .
Suppose an array contains @arraycontent=(‘ab’, ‘cd’, ‘ef’, ‘gh’). How to print all the contents of the given array?
@arraycontent=('ab', 'cd', 'ef', 'gh')
foreach (@arraycontent)
{
 print "$_\n";
}
38 .
Remove the duplicate data from @array=(“perl”,”php”,”perl”,”asp”)
sub uniqueentr
 {
  return keys %{{ map { $_ => 1 } @_ }};
 }
  @array = ("perl","php","perl","asp");
  print join(" ", @array), "\n";
  print join(" ", uniqueentr(@array)), "\n";
Array slicing allows a user to retrieve more than one element of an array at once.
 
For Example :
@myarray = (1,2,3,4,5);
@subarray = @myarray [0,1];
Print (“@subarray\n”);
Output : 1 2
 
Thus we can ‘Slice’ the existing array and retrieve its elements.
 
We can also slice an array into large slices using the “List-range operator” of Perl. List-range operator allows us to specify a range which will return all the elements in that range.
 
Example: 
@daysOfMonth = (1..31); #daysOfMonth will contain 1 to 31 elements.
@fortnight = @daysOfMonth[1..15];
This will assign a slice consisting of the first 15 elements to fortnight array.
DIE and EXIT are two library functions in Perl to exit the program. The difference between DIE and EXIT is that DIE exits the program and prints a specified message. Exit simply exits the program.
 
Example :
open(myfile,filename) ||DIE(“File cannot be opened\n”);
The above line of code will print a message “File cannot be opened” in case if open fails and then exits the program.
In Perl, all input or actual parameters of the subroutine are stored in an array ‘@_’. In other words, array @_ is used as an alias for subroutine arguments.
 
Let’s demonstrate this with an example :
print &amp;sum(1..4),”\n”;
sub sum{
my $sum = 0;
for my $i(@_){
$sum += $i;
}
return $sum;
}
In this example, we are calculating the sum of elements 1 to 4. We pass these elements as a range to a subroutine. In the subroutine code, @_ that contains parameters is iterated to find the sum and then the sum is returned.
Lexical scoping is done with my operator. A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements. The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed.
The context of a subroutine or statement is defined as the type of return value that is expected. This allows you to use a single function that returns different values based on what the user is expecting to receive. For example, the following localtime() returns a string when it is called in scalar context, but it returns a list when it is called in list context.
my $datestring = localtime( time );
In this example, the value of $timestr is now a string made up of the current date and time, for example, Thu Dec 31 12:22:31 2021. Conversely −
($sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst) = localtime(time);
Now the individual variables contain the corresponding values returned by localtime() subroutine.
A circular reference occurs when two references contain a reference to each other. You have to be careful while creating references otherwise a circular reference can lead to memory leaks. Following is an example :
#!/usr/bin/perl
my $foo = 100;
$foo = \$foo;
 
print "Value of foo is : ", $$foo, "\n";
When above program is executed, it produces the following result :
Value of foo is : REF(0x9aae38)
The syntax used in Perl is
grep BlOCK LIST
grep ( EXPR, LIST )
BLOCK : It contains one or more statements delimited by braces, the last statement determines in the block whether the block will be evaluated true or false.

EXPR : It represents any expression that supports $, particularly a regular expression. Against each element of the list, expression is applied, and if the result of the evaluation is true, the current element will be attached to the returned list

LIST : It is a list of elements or an array
Chop function eliminates the last character from expr, each element of the list

Chomp function eliminates the last character from an expr or each element of the list if it matches the value of $/. It is considered better than chop as it only removes the character if there is a match.
In Perl, Polymorphism means the methods defined in the base class will always over-ride the methods defined in the parent class.
STDIN : The STDIN file handle is used to read from the keyboard

STDOUT :
It is used to write into the screen or another program

STDERR :
It is also used to write into a screen. STDERR is a standard error stream that is used in Perl.
The Perl goto statement is the jump statement. It transfers control by jumping to another label inside a loop.
 
There are three goto forms :

Goto LABEL : at this label, execution stops at the current point and resumes at the point where the label is specified. You cannot jump to a point inside a subroutine using Goto Label.

Goto NAME : it replaces the subroutine that is currently executing with a call to a particular subroutine instead. It automatically calls a different subroutine dynamically selects alternative routines.

Goto EXPR : it is an extension of Goto label.
Like other languages, Perl also provides comment facility in its code. There are a single line and multi-line comment.
 
For single line comment : use # before the line you want to comment.
 
For multi-line comment : use =begin and =cut statement before and after the lines respectively you want to comment.
A regular expression is a string of characters that defines a specific pattern.
 
There are three regular expression operators inside Perl :
 
* Matching regular expression operator, m//
* Substitute regular expression operator, s///
* Transliterate regular expression operator, tr///
52 .
What $! in Perl?
The $! is a built-in error reporting variable in Perl. It tells us the reason for the error and prints it. It prints what the operating system tells it.
DBI stands for Database Independent Interface. In Perl, the database is accessed using DBI module. It is a third party module provided by CPAN. It supports all the major database systems. It provides an abstraction layer between Perl code and database.
Once you have given Perl commit command, you can't retrieve back the changes you made.
 
Syntax :
$dbh->commit or die $dbh->errstr;
If you want to revert the changes made during the operation, call rollback command.
 
Syntax :
$dbh->rollback or die $dbh->errstr; 
By specifying RaiseError option, your errors will be handled automatically by Perl. Your program will be aborted on encountering an error rather than running a failure code. Its value can be either 1 or 0.
* err
* errstr
* trace
* rows
The socket is a procedure which helps to establish a virtual connection between different processes over a network.
 
In socket programming, client and server-side script are made which communicate through each other over TCP/IP protocol.
The closure is a block of code that is used to capture the environment where it is defined, and it captures lexical variables that the block consists of.