Perl Interview Questions

Difference between the variables in which chomp function work ?

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

Create a function that is only available inside the scope where it is defined ?

$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

Which feature of Perl provides code reusability ? Give any example of that feature.

Inheritance feature of Perl provides code reusability. In inheritance, the child class can use the methods and property of parent class
Package Parent;
Sub foo
{
print(“Inside A::foo\n”);
}
package Child;
@ISA = (Parent);
package main;
Child->foo();
Child->bar();

In Perl we can show the warnings using some options in order to reduce or avoid the errors. What are that options?

The -w Command-line option: It will display the list if warning messages regarding the code.
strict pragma: It forces the user to declare all variables before they can be used using the my() function.
Using the built-in debugger: It allows the user to scroll through the entire program line by line.

Write the program to process a list of numbers?

The following program would ask the user to enter numbers when executed and the average of the numbers is shown as the output:
$sum = 0;
$count = 0;
print “Enter number: “;
$num = <>;
chomp($num);
while ($num >= 0)
{
$count++;
$sum += $num;
print “Enter another number: “;
$num = <>;
chomp($num);
}
print “$count numbers were entered\n”;
if ($count > 0)
{
print “The average is “,$sum/$count,”\n”;
}
exit(0);

Does Perl have objects? If yes, then does it force you to use objects? If no, then why?

Yes, Perl has objects and it doesn’t force you to use objects. Many object oriented modules can be used without understanding objects. But if the program is too large then it is efficient for the programmer to make it object oriented.

Can we load binary extension dynamically?

Yes, we can load binary extension dynamically but your system supports that. If it doesn’t support, then you can statically compile the extension.

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

How do I replace every TAB character in a file with a comma?

perl -pi.bak -e ‘s/\t/,/g’ myfile.txt

In Perl, there are some arguments that are used frequently. What are that arguments and what do they mean?

-w (argument shows warning)
-d (use for debug)
-c (which compile only not run)
-e (which executes)
We can also use combination of these like:
-wd

How many types of primary data structures in Perl and what do they mean?

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.

Which functions in Perl allows you to include a module file or a module and what is the difference between them?

“use”

  1. The method is used only for the modules (only to include .pm type file)
  2. The included objects are verified at the time of compilation.
  3. We don’t need to specify the file extension.
  4. loads the module at compile time.

“require”

  1. The method is used for both libraries and modules.
  2. The included objects are verified at the run time.
  3. We need to specify the file Extension.
  4. Loads at run-time.

suppose we have a module file as “Module.pm”
use Module;
or
require “Module.pm”;
(will do the same)

How can you define “my” variables scope in Perl and how it is different from “local” variable scope?

$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.

Which guidelines by Perl modules must be followed?

Below are guidelines and are not mandatory
The name of the package should always begin with a capital letter.
The entire file name should have the extension “.pm”.
In case no object oriented technique is used the package should be derived from the Exporter class.
Also if no object oriented techniques are used the module should export its functions and variables to the main namespace using the @EXPORT and @EXPOR_OK arrays (the use directive is used to load the modules).

How the interpreter is used in Perl?

Every Perl program must be passed through the Perl interpreter in order to execute. The first line in many Perl programs is something like:
#!/usr/bin/perl
The interpreter compiles the program internally into a parse tree. Any words, spaces, or marks after a pound symbol will be ignored by the program interpreter. After converting into parse tree, interpreter executes it immediately. Perl is commonly known as an interpreted language, is not strictly true. Since the interpreter actually does convert the program into byte code before executing it, it is sometimes called an interpreter/compiler. Although the compiled form is not stored as a file.

“The methods defined in the parent class will always override the methods defined in the base class”. What does this statement means?

The above statement is a concept of Polymorphism in Perl. To clarify the statement, let’s take an example:
[perl]
package X;
sub foo
{
print(“Inside X::foo\n”);
}
package Z;
@ISA = (X);
sub foo
{
print(“Inside Z::foo\n”);

}

package main;

Z->foo();
[/perl]
This program displays:
Inside Z::foo
– In the above example, the foo() method defined in class Z class overrides the inheritance from class X. Polymorphism is mainly used to add or extend the functionality of an existing class without reprogramming the whole class.

For a situation in programming, how can you determine that Perl is a suitable?

If you need faster execution the Perl will provide you that requirement. There a lot of flexibility in programming if you want to develop a web based application. We do not need to buy the license for Perl because it is free. We can use CPAN (Comprehensive Perl Archive Network), which is one of the largest repositories of free code in the world.

Write syntax to add two arrays together in perl?

 @arrayvar = (@array1,@array2);
To accomplish the same, we can also use the push function.

How many types of operators are used in the Perl?

Arithmetic operators
+, – ,*
Assignment operators:
+= , -+, *=
Increment/ decrement operators:
++, —
String concatenation:
‘.’ operator
comparison operators:
==, !=, >, < , >=
Logical operators:
&&, ||, !

If you want to empty an array then how would you do that?

We can empty an array by setting its length to any –ve number, generally -1 and by assigning null list
use strict;
use warnings;
my @checkarray;
if (@checkarray)
{
print “Array is not empty”;
}
else
{
print “Array is empty”;
}

Where the command line arguments are stored and if you want to read command-line arguments with Perl, how would you do that?

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

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”;
}

What is the use of -w, -t and strict in Perl?

When we use –w, it gives warnings about the possible interpretation errors in the script.
Strict tells Perl to force checks on the definition and usage of variables. This can be invoked using the use strict command. If there are any unsafe or ambiguous commands in the script, this pragma stops the execution of the script instead of just giving warnings.
When used –t, it switches on taint checking. It forces Perl to check the origin of variables where outside variables cannot be used in sub shell executions and system calls

Write a program to download the contents from www.perlinterview.com/answers.php website in Perl?

#!/usr/bin/perl
use strict;
use warnings;
use LWP::Simple;
my $siteurl = ‘www.perlinterview.com/answers.php’;
my $savefile = ‘content.kml’;
getstore($siteurl, $savefile);

Which has the highest precedence, List or Terms? Explain?

Terms have the highest precedence in Perl. Terms include variables, quotes, expressions in parenthesis etc. List operators have the same level of precedence as terms. Specifically, these operators have very strong left word precedence.

Where the command line arguments are stored and if you want to read command-line arguments with Perl, how would you do that?

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

Suppose an array contains @array content=(‘ab’, ‘cd’, ‘ef’, ‘gh’). How to print all the contents of the given array?

2
3
4
5
6
7
8
9
@arraycontent=(ab,cd,ef,gh)
foreach (@array content)
{
print “$_\n”;
}

What is the use of -w, -t and strict in Perl?

When we use –w, it gives warnings about the possible interpretation errors in the script.

Strict tells Perl to force checks on the definition and usage of variables. This can be invoked using the use strict command. If there are any unsafe or ambiguous commands in the script, this pragma stops the execution of the script instead of just giving warnings.

When used –t, it switches on taint checking. It forces Perl to check the origin of variables where outside variables cannot be used in sub shell executions and system calls

Write a program to download the contents from www.perlinterview.com/answers.php website in Perl.

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/perl
use strict;
use warnings;
use LWP::Simple;
my $siteurl = ‘www.perlinterview.com/answers.php’;
my $savefile = ‘content.kml’;
getstore($siteurl, $savefile);

Which has the highest precedence, List or Terms? Explain?

Terms have the highest precedence in Perl. Terms include variables, quotes, expressions in parenthesis etc. List operators have the same level of precedence as terms. Specifically, these operators have very strong left word precedence.

List the data types that Perl can handle?

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

Write syntax to use grep function?

1
2
3
grep BLOCK LIST
grep (EXPR, LIST)

What is the use of -n and -p options?

The -n and -p options are used to wrap scripts inside loops. The -n option makes the Perl execute the script inside the loop. The -p option also used the same loop as -n loop but in addition to it, it uses continue. If both the -n and -p options are used together the -p option is given the preference.

What is the usage of -i and 0s options?

The -i option is used to modify the files in-place. This implies that Perl will rename the input file automatically and the output file is opened using the original name. If the -i option is used alone then no backup of the file would be created. Instead -i.bak causes the option to create a backup of the file.

Write a program that explains the symbolic table clearly?

In Perl, the symbol table is a hash that contains the list of all the names defined in a namespace and it contains all the functions and variables. For example:

How can you use Perl warnings and what is the importance to use them?

The Perl warnings are those in which Perl checks the quality of the code that you have produced. Mandatory warnings highlight problems in the lexical analysis stage. Optional warnings highlight cases of possible anomaly.

Which statement has an initialization, condition check and increment expressions in its body? Write a syntax to use that statement?

1
2
3
4
5
6
7
for ($count = 10; $count >= 1; $count)
{
print “$count “;
}

How can you replace the characters from a string and save the number of replacements?

Perl

1
2
3
4
5
6
7
8
9
10
11
12
13
#!usr/bin/perl
use strict;
use warnings;
my $string=“APerlAReplAFunction”;
my $counter = ($string =~ tr/A//);
print “There are $counter As in the given string\n”;
print $string;

Remove the duplicate data from @array=(“perl”,”php”,”perl”,”asp”)?

Perl

1
2
3
4
5
6
7
8
9
10
11
12
13
sub uniqueentr
{
return keys %{{ map { $_ => 1 } @_ }};
}
@array = (“perl”,“php”,“perl”,“asp”);
print join(“ “, @array), “\n“;
print join(“ “, uniqueentr(@array)), “\n;

How can information be put into hashes?

When a hash value is referenced, it is not created. It is only created once a value is assigned to it. The contents of a hash have no literal representation. In case the hash is to be filled at once the unwinding of the hash must be done. The unwinding of hash means the key value pairs in hash can be created using a list, they can be converted from that as well. In this conversion process the even numbered items are placed on the right and are known as values. The items placed on the left are odd numbered and are stored as keys. The hash has no defined internal ordering and hence the user should not rely on any particular ordering.

Example of creating hash:

Why Perl aliases are considered to be faster than references?

In Perl, aliases are considered to be faster than references because they do not require any dereferencing.

How can memory be managed in Perl?

Whenever a variable is used in Perl, it occupies some memory space. Since the computer has limited memory the user must be careful of the memory being used by the program. For Example:

 

On execution of above program, after reading a file it will print the first word of each line into another file. If the files are too large then the system would run out of memory. To avoid this, the file can be divided into sections.

How can you create anonymous subroutines?

1
2
3
4
5
6
7
sub BLOCK
sub PROTO BLOCK
sub ATTRS BLOCK
sub PROTO ATTRS BLOCK

What do you mean by context of a subroutine?

It is defined as the type of return value that is expected. You can use a single function that returns different values.

List the prefix dereferencer in Perl ?

$-Scalar variables

%-Hash variables

@-arrays

&-subroutines

Type globs-*myvar stands for @myvar, %myvar.

In CPAN module, name an instance you use?

In CPAN, the CGI and DBI are very common packages.

What are the advantages of c over Perl?

There are more development tools for C than for PERL. PERL execute slower than C programs. Perl appears to be an interpreted language but the code is complied on the fly. If you don’t want others to use your Perl code you need to hide your code somehow unlike in C. Without additional tools it is impossible to create an executable of a Perl program.

“Perl regular expressions match the longest string possible”. What is the name of this match?

It is called as “greedy match” because Perl regular expressions normally match the longest string possible.

How can you call a subroutine and identify a subroutine?

‘ &myvariable’ is used to call a sub-routine and ‘&’ is used to identify a sub-routine.

What is use of ‘->’ symbol?

In Perl, ‘->’ symbol is an infix dereference operator. if the right hand side is an array subscript, hash key or a subroutine, then the left hand side must be a reference.

Where do we require ‘chomp’ and what does it mean?

We can eliminate the new line character by using ‘chomp’. It can used in many different scenarios.For example:

What does the’$_’ symbol mean?

The ‘$_’ is a default variable in Perl and $_ is known as the “default input and pattern matching space.

What interface used in PERL to connect to database? How do you connect to database in Perl?

We can connect to database using DBI module in Perl.

List the operator used in Perl?

Operators used in Perl are

 

  • String Concatenation à ‘.’
  • Comparison Operators à ==, !=, >,< , >=
  • Logical Operators à &&, ll , !
  • Assignment Operators à + = ,- + , *=
  • Increment and decrement Operators à ++ ,-
  • Arithmetic Operators à +, – ,*

Explain which feature of PERL provides code reusability?

To provide code re-usability in PERL inheritance feature is used. In Inheritance, the child class can use the methods and property of the parent class.

Mention the difference between die and exit in Perl?

Die will print a message to the std err before ending the program while Exit will simply end up the program.

In Perl, what is grep function used for?

To filter the list and return only those elements that match certain criteria Perl grep function is used.

What is the syntax used in Perl grep function?

The syntax used in Perl is

 

a) grep BlOCK LIST

b) 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

Explain what is the scalar data and scalar variables in Perl?

Scalar in Perl means a single entity like a number or string. So, the Java concept of int, float, double and string equals to perls scalar and the numbers and strings are exchangeable. While scalar variable is used to store scalar data. It uses $ sign and followed by one or more alphanumeric characters or underscore. It is a case sensitive.

What does -> symbol indicates in Perl?

In Perl, the arrow – > symbol is used to create or access a particular object of a class.

Mention how many ways you can express string in Perl?

You can express string in Perl in many ways

 

For instance “this is guru99.”

 

  • qq/this is guru99 like double quoted string/
  • qq^this is guru99 like double quoted string^
  • q/this is guru99/
  • q&this is guru99&
  • q(this is guru99)

Explain USE and REQUIREMENT statements?

  • REQUIRE statement: It is used to import functions with a global scope such that their objects and functions can be accessed directly

 

Example: Require Module,

Var=module::method(); //method called with the module reference

 

  • USE statements are interpreted and are executed during parsing, while during run time the require statements are executed.

 

Example: Use Module

Var=method(); //method can be called directly

Explain what is Chop & Chomp function does?

  • 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.

Mention what is CPAN?

CPAN means Comprehensive Perl Archive Network, a large collection of Perl software and documentation.

Explain what is Polymorphism in Perl?

In Perl, Polymorphism means the methods defined in the base class will always over-ride the methods defined in the parent class.

Mention what are the two ways to get private values inside a subroutine or block?

There are two ways through which private values can be obtained inside a subroutine or block

 

  • Local Operator: On global variables only this operator can operate. The value of the private variable is saved on the Local Operator and makes the provision to restore them at the end of the block
  • My Operator: To define or create a new variable this operator can be used. Variable that is created by My Operator will always be declared private to block inside which it is defined.

Explain what is STDIN, STDOUT and STDERR?

  • 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.

What is the closure in PERL?

The closure is a block of code that is used to capture the environment where it is defined. It particularly captures any lexical variables that block consists of and uses in an outer space.

Explain what is Perl one liner?

One liner is one command line programs and can be executed from the command line immediately.

 

For example,

# run program under the debugger

perl-d my_file

Explain what is lvalue?

An lvalue is a scalar value which can be used to store the result of any expression. Usually, it appears at the left-hand side of the expression and represent a data space in memory.

Explain what is the function that is used to identify how many characters are there in a string?

To tell how many characters are there in a string, length () function is used.

Explain what are prefix de referencer and list them out?

Using a particular prefix when you dereference a variable, they are called prefix dereferencer.

 

  • $- Scalar variables
  • %-Hash variables
  • @-Arrays
  • &-Subroutines
  • Type globs-*myvar stands for @myvar, %myvar

Explain what is the function of Return Value?

The Return Value function returns a reference to an object blessed into CLASSNAME.

How to read a directory in Perl?

To read a directory in Perl, readdir function is used. In scalar context, it will return each item one by one. In list context, it will return all the content of directory in one statement. So list context uses more memory than scalar context.

How to remove a directory in Perl?

To remove a directory in Perl, rmdir function is used. The directory which you want to remove should be empty before removing it.

How to change a directory in Perl?

To change a directory in Perl, chdir function is used. To change a directory and go inside a new directory you need required permission.

How to close a directory in Perl?

To close a directory in Perl, closedir function is used. This function officially shut down the connection between directory handle and directory.

What is chop() function in Perl?

Perl chop() function removes last character from a string regardless of what that character is. It returns the chopped character.

What is chomp() function in Perl?

Perl chomp() function removes any new line character from end of the string. It returns the number of characters removed from the string.

What does die() function do in Perl?

Perl die() function gives us a proper error message. It immediately terminates the script on encountering an error.

Explain the difference between die and exit in Perl?

The die function prints the standard error message then exits the program. Whereas, the exit function terminates the program without giving any error message.

What $! in Perl?

The $! Is a built-in error reporting variable in Perl. It tells us the reason for error and print it. It prints what it is told by operating system.

What is warn function in Perl?

The warn function gives the warning on encountering an error but does not exit the script. Script keeps on running.

What is confess function in Perl?

The confess function is used within the Carp standard library for error handling.

What is eval function in Perl?

The eval function is a built-in function in Perl which is used to detect normal fatal error. It is supplied with a code block instead of passing into string.

What is Perl DBI?

DBI stands for Database Independent Interface. In Perl, 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.

What does 'do' statement do in Perl?

The do statement is used in Perl database. It is a shortcut to perform all the CRUD operation. If it is succeeded, it returns true, otherwise false.

What is 'commit' command in Perl?

Once you have given Perl commit command, you can’t retrieve back the changes you made.

Syntax:

  1. $dbh->commit or die $dbh->errstr;

What is 'rollback' command in Perl?

If you want to revert the changes made during the operation, call rollback command.

Syntax:

  1. $dbh->rollback or die $dbh->errstr;

What is automatic error handling in Perl?

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.

What are some common methods to all handles in Perl?

  • err
  • errstr
  • trace
  • rows

What does localtime() do in Perl?

The localtime() function if used without any argument, returns the current date and time according to the system.

What is the use of now constructor in Perl?

The now constructor creates DateTime object displaying current date and time using DateTime module.

Explain gmtime() function in Perl?

This function works similar to localtime() with only one difference that returned value is localized for the standard Greenwich time zone.

What is epoch time Perl?

The epoch time refers to the number of seconds after a specific date and time. This specific date and time varies for different operating systems. For example, for Unix it is January 1, 1970.

What is POSIX in Perl?

POSIX – Perl interface to IEEE Std 1003.1

The POSIX module allows you to access all the standard POSIX identifiers. This module provides much more functions than any other module.

Explain strftime() function in Perl?

The Perl POSIX strftime() function is used to format date and time with the specifiers preceded with (%) sign.

Explain socket programming in Perl?

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 is made which communicate through each other over TCP/IP protocol.

Explain '->' in Perl?

It is a symbolic link which links one file name to a new file name.

For example, in file1 -> file2, if we read file1, we will end up reading file2.

Explain tell function in Perl?

The tell function finds your position within a file. This is the first thing you need to do while file handling.

What does file test operators do in Perl?

File test operators check miscellaneous information about a file. Like type of file, file byte size, its UID or GID, etc.

How to open a directory in Perl?

To open a directory in Perl, opendir function is used. It returns true on success or false on failure.

Summary
Review Date
Reviewed Item
Very Helpful! Perl Interview Questions and Answers, Thank you Iteanz for sharing.
Author Rating
51star1star1star1star1star