Do you know that? Companies of all sizes will hire twice as many online workes next

Contact Email:

See right interview answers on 30 common job interview questions

Collapse | Expand

1. Count no. of occurrences of a word ?

• #!/usr/bin/perl  
           • use strict;  
           • use warnings;  
           • ####Example 1  
           • my $text = 'perl is good, perl is better, perl is best';  
           • my $count = ($text =~ s/perl/perl/g);  
           • print "\n No. of occurrences of 'perl' is:", $count;  
           • print "\n";  
           • ####Example 2  
           • my $p = "india s great country india india super";  
           • my $find = "india";  
           • my $count = () = $p =~ /$find/g;  
           • #or  
           • my ($count) = $p =~ /$find/g;  
           • print "\n Count:", $count;  
           • print "\n";  
           • ####Example 3  
           • use strict;  
           • my($test,$number);  
           • $test = "12344tyyyyy456";  
           • $number = ($test =~ tr/[0-9]/[0-9]/);  
           • print "Number of digits in variable is :- $number ";  
           • 1;

2. 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));};        

3. Define Chop Vs Chomp?

Chop : removes any last char from the line
  This function removes the last character of a string and returns that character
  Chomp : removes only special chars from the end of the line
  It removes characters at the end of strings corresponding to the $INPUT_LINE_SEPARATOR ($/)
 It returns the number of characters removed.

  • <b>#chop()  
         • $a = "abcdefghij";  
         • chop($a);  
         • print $a;  #this would return 'abcdefghi'  
         • $a = "abcdefghij";  
         • $b = chop($a);  
         • print $b;  #this would return 'j'  
         • </b>

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

5. Explain control structure in perl?

Control Structures:
   If / unless statements : If similar to the if in C.
  Eg of unless.
  When you want to leave the then part and have just an else part we use unless.
   While / until statements:
  While similar to the while of C.
  Eg until.
  Until(some expression){}.
  So the statements are executed till the condition is met.
  For is also similar to C implementation.
   For statements: For is also similar to C implementation.
   Foreach statements: This statement takes a list of values and assigns them one at a time to a scalar variable, executing a block of code with each successive assignment.
  Eg: Foreach $var (list) {}.
   Last , next , redo statements:
  Last is similar to break statement of C. Whenever you want to quit from a loop you can use this.
  To skip the current loop use the next statement. It immideately jumps to the next iteration of the loop.
 The redo statement helps in repeating the same iteration again.

6. 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 ";


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.

7. How do I do fill_in_the_blank for each file in a directory?

Here's code that just prints a listing of every file in the current directory:

#!/usr/bin/perl -w

opendir(DIR, ".");

@files = readdir(DIR);


foreach $file (@files) {

print "$filen";


8. How do I set environment variables in Perl programs?

you can do something like this:

$ENV{'PATH'} = '...';

As you may remember, "%ENV" is a special hash in Perl that contains the value of all your environment variables.

Because %ENV is a hash, you can set environment variables just as you'd set the value of any Perl hash variable. Here's how you can set your PATH variable to make sure the following four directories are in your path::

$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/home/yourname/bin';									

9. How do you declare function and call function in perl?

Function Declaration: The keyword sub describes the function.
  So the function should start with the keyword sub.
  Example: sub addnum { …. }.
  It should be preferably either in the end or in the beginning of the main program to improve readability and also ease in debugging.
  Function Calls:
  $Name = &getname();
  The symbol & should precede the function name in any function call.
  Parameters of Functions:
   We can pass parameter to the function as a list .
   The parameter is taken in as a list which is denoted by @_ inside the function.
  So if you pass only one parameter the size of @_ list will only be one variable. If you pass two parameters then the @_ size will be two and the two parameters can be accessed by $_[0],$_[1] ....

10. How do you separate executable statements in perl?

semi-colons separate executable statements
  my( $Hour ) = $Tiim[2];
  my( $Min ) = $Tiim[1];
  my( $Sec ) = $Tiim[0];
  my( $limdate ) = `$ENV{'SOURCE_DIR_ETD_BIN'}/getDate -f DDMMYYYY`;
  chomp $limdate;
  Note: Practical extraction and report language
  Note: No main() function – code executed top-down.
  Note: { } delimit blocks, loops, subroutines
  if( defined $opts{'f'} ) {
  $Force_Rerun = $opts{'f'};
  } else {
  $Force_Rerun = "N";

11. How many types of operators are used in the Perl?

Arithmetic operators

+, – ,*

Assignment operators:

+= , -+, *=

Increment/ decrement operators:

++, —

String concatenation:

‘.’ operator

comparison operators:

==, !=, >, < , >=

Logical operators:

&&, ||, !

12. How to get unique elements from Arrays?

• #! /usr/bin/perl  
           • use strict;  
           • use warnings;  
           • use Data::Dumper;  
           • #unique elements from different arrays  
           • my @array1 = (10,20,30);  
           • my @array2 = (11,22,33);  
           • my @array3 = (10,20,30);  
           • my %uniq_arr;  
           • for my $each (@array2, @array3, @array1) {  
           • $uniq_arr{$each}++;  
           • }  
           • print "\n", $_ for (keys %uniq_arr),"\n";  
           • 1;

13. How to open and read data files with Perl?

Data files are opened in Perl using the open() function. When you open a data file, all you have to do is specify (a) a file handle and (b) the name of the file you want to read from.

As an example, suppose you need to read some data from a file named "checkbook.txt". Here's a simple open statement that opens the checkbook file for read access: open (CHECKBOOK, "checkbook.txt"); In this example, the name "CHECKBOOK" is the file handle that you'll use later when reading from the checkbook.txt data file. Any time you want to read data from the checkbook file, just use the file handle named "CHECKBOOK".

Now that we've opened the checkbook file, we'd like to be able to read what's in it. Here's how to read one line of data from the checkbook file:

$record = < CHECKBOOK > ;

After this statement is executed, the variable $record contains the contents of the first line of the checkbook file. The "<>" symbol is called the line reading operator.

To print every record of information from the checkbook file

open (CHECKBOOK, "checkbook.txt") || die "couldn't open the file!";

while ($record = < CHECKBOOK >) {

print $record;



14. How to reverse hash or Look up a hash by value instead of key?

But remember keys are unique but values are not, so before reversing the original array values

 should be unique, after reverse these values become keys of reversed array. Otherwise things will not work out in ur way.
  Anyways just give a try
  # Eg: %hash = ( a => 10, b => 10, c => 10, d => 10);
      • #!/usr/bin/perl  
           • use strict;  
           • use warnings;  
           • ### The following is good and easy to use but not tat much efficient in
           •  terms of space, as it needs to keep a copy of the hash  
           • %hash = ( a => 10, b => 20, c => 30, d => 40);  
           • print "\n Hash before reverse:", Dumper(\%hash);  
           • %reverse_hash = reverse %hash; # It will reverse the hash  
           • print "\n Hash after reverse :", Dumper(\%reverse_hash);  
           • print "\n";  
           • ### The following is space efficient  
           • %hash = ( a => 10, b => 20, c => 30, d => 40);  
           • print "\n Hash before reverse:", Dumper(\%hash);  
           • while (($key, $value) = each %hash) {  
           •     $hash{$value} = $key;  
           • }  
           • print "\n Hash after reverse :", Dumper(\%hash);  
           • print "\n";  
           • 1;

15. How to substitute a string?

  Another use for (parenthesis)

16. How to use Ciel and Floor Functions?

#!F:\Perl\bin\perl -w
  use strict;
  use POSIX; #ciel and floor available in POSIX module
  $a = ceil(3.45);
  print "\n $a"; #gives o/p as '4'
  $b = floor(3.45);
  print "\n $b"; #gives o/p as '3'
  printf("\n%.3f", 3.1415926535); #gives output as 3.142, rounds of to 3 digits
  #For Rounding use printf and sprintf

17. How to write a File?

• #! /usr/bin/perl  
           • use strict;  
           • use warnings;  
           •  my $filename = '/path/to/your/data.txt';  
           •  if (-e $filename) {  
           •     print "File Exists!";  
           •  }  
           •  unless (-e $filename) {  
           •     print "File Doesn't Exist!";  
           •  }  
           •  open (MYFILE, ">>$filename");  
           •  print MYFILE "Bob\n";  
           •  close (MYFILE);  
           • 1;  

use the > single greater than symbol to tell the open function that you want a fresh file each time.
use the >> to append to the file data.txt


18. 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";




print "Array is empty";


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

20. 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:


21. IP Address Validation in Perl?

• <b>#! /usr/bin/perl  
         • use strict;  
         • use warnings;  
         • print "Enter an ip address: ";  
         • $ans = <stdin>;  
         • #chomp($ans);  
         • if ($ans =~ m/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)  
         • {  
         •    if ( ($1>0) && ($1<=255) && ($2<=255) && ($3<=255) &&($4<=255))  
         •    {  
         •        print "An IP Address";  
         •    }  
         •    else   
         •    {  
         •        print "Not an IP Address";  
         •    }  
         • }  
         • else  
         • {  
         •    print "Not an IP Address";  
         • }  
         • </b>

22. Make first letter of every word in a string to Upper case?

• #!/usr/bin/perl  
           • use strict;  
           • use warnings;  
           • my $text = 'india is a great country';  
           • print "\n Before:", $text; # india is a great country  
           • $text =~ s/(\w+)/\u$1/g; # \u option is used  
           • print "\n After :", $text,"\n"; # India Is A Great Country

23. Perl is Compiler/Interpreter ?

Every Perl program must be passed through the Perl interpreter in order to execute. The first line in many Perl programs is something like:
  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.

24. 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";


25. What are array functions?

Array functions:
   Grep
   Join
   Map
   Pop
   Push
   Shift
   Unshift
   Scalar
   Lenghth of an array
   Array swapping(Slice)
   Splice
   Split
   Sort
  Context

26. What are scalar functions?

Forces EXPR to be interpreted in scalar context and returns the value of EXPR.
  Scalar Functions:
   Chop
   Chomp
   Defined
   Undef
   Uc,lc,ucfirst,lcfirst
   My and local and our
   Ref – after reference
   Return
   Reverse
   Index
   Substr
   Context – not a keyword
  Legnth

27. What do you mean by a shebang?

To tell the OS that perl should execute the following code
  Note: MUST be first line of the file.. no comments, no spaces prior to the shebang
 Standard: #!/usr/bin/perl

28. What is difference between C++ and Perl?

Perl can have objects whose data cannot be accessed outside its class, but C++ cannot.

Perl can use closures with unreachable private data as objects, and C++ doesn't support closures. Furthermore, C++ does support pointer arithmetic via `int *ip = (int*)&object', allowing you do look all over the object. Perl doesn't have pointer arithmetic. It also doesn't allow `#define private public' to change access rights to foreign objects. On the other hand, once you start poking around in /dev/mem, no one is safe.

29. What is list variable?

 They are like arrays. It can be considered as a group of scalar variables.
   They are always preceded by the @symbol.
  – Eg @names = ("betty","veronica","tom");
   Like in C the index starts from 0.
   If you want the second name you should use $names[1] ;
   Watch the $ symbol here because each element is a scalar variable.
   $ Followed by the listvariable gives the length of the list variable.
 – Eg $names here will give you the value 3.

30. What is perl hash?

Hashes are like arrays but instead of having numbers as their index they can have any scalars as index.
   Hashes are preceded by a % symbol.
  – Eg we can have %rollnumbers = ("A",1,"B",2,"C",3);

Functions for Hashes:
   Each
   Keys
   Values
   Exists
   Delete
   Hash length
   Sort
  Context

31. What is regex?

 A regular expression (or regex) is a simple, rather mindless way of matching a series of symbols to a pattern you have in mind.
   The basic ideas of regex are simple, but powerful
   We want to know whether a text string matches a pattern.
  $mystring=~/blahblah/ ;
  Matching Anything
   /sh[ou]t/

 /sh.t/
  Matching several characters
   /sh.+t/
   /sh.*t/
  Escaping confusion
   /a \+ b/
   /a \.b/
   /a \* b/
  Case iNseNSItivITy
   /sensitive/
   /sensitive/ I
   s - Treat the whole string as one line, so that even /./ will match a "newline" character.
  More matching tricks
   ? - matches zero or one of the preceding character
   {n} - matches n copies of the preceding character!
   {n,m} - matches at least n but not more than m copies of the preceding character
   {n,} - matches at least n copies of the preceding character
  Extract text from the match
   /alpha(.+)gamma/
   /<(.+?)>.+<\/\1>/
  Matching fancy characters
   /[c-q]/
   /[cdefghijklmnopq]/
   /[a-d0-4]
  /[^0-4]/

32. What is the use of print command?

The "print command" is used to write outputs on the screen.
 Print "Hello World"; Prints "Hello World" on the screen. It is very similar to printf statement in C.

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

34. 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;





35. Why we use "use lib $path"?

If we are trying to add a module or library files in our program using require or use statement then it will search that module or library files in the Perl's default search path (@INC).
    The statement 'use lib' is used to add the directories to default search path.
    So if the module or library file is not located in the Perl's default search path then it will find the library files in the path we have given with the use lib $path.

36. Write a program to concatenate the $firststring and $secondstring and result of these strings should be separated by a single space?


$result = $firststring . ” “.$secondstring;


$firststring = "abcd";
$secondstring = "efgh";
$combine = "$firststring $secondstring";
print "$Combine\n";

37. Write the program to process a list of numbers?

$count = 0;
    print "Enter number: ";
    $num = &lt;&gt;;
    while ($num &gt;= 0)
    $sum += $num;
    print "Enter another number: ";
    $num = &lt;&gt;;
    print "$count numbers were entered\n";
    if ($count &gt; 0)
    print "The average is ",$sum/$count,"\n";