Site menu:

Perl Interview Questions

Asked in IT companies
 
Please send your questions to Shaji Kalidasan <shajiindia@yahoo.com> and it will be published here.
 
If this page was useful to you, please help others find it:
 

 
Company : Wipro Technologies
  • Asked To : Anand Seshadri
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you sort dates in chronological order?
Here is one way to do it
 
my @dates = ( "22/08/2004", "04/02/2001", "17/04/2013", "12/01/1977", "02/11/2011" );
@dates = sort {	join( '', ( split '/', $a )[ 2, 1, 0 ] ) cmp join( '', ( split '/', $b )[ 2, 1, 0 ] )
              } @dates;
print "@dates";


 
Company : Wipro Technologies
  • Asked To : Anand Seshadri
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you check if a given string is a valid number which Perl can recognize?
Here is one way to do it
 
use Scalar::Util qw(looks_like_number);

my @words =
  qw/9 8.76  dhoni 0.00981 raina 0.000000001 1cd 2.8e12 55apples oranges65 0xff 0377 0b11111111/;

foreach my $val (@words) { 
	print "$val is", looks_like_number($val) ? '' : ' not', " a number\n";
}


 
Company : Nokia
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you reverse a string without using Perl's reverse built-in function?
Here is one way to do it
 
use strict;
use warnings;

my $str = "Japan is the land of rising sun.";
my @string = split '', $str;
for ( my $i = $#string ; $i >= 0 ; $i-- ) {
	print $string[$i];
}


 
Company : Nokia
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you sort keys in a hash?
Here is one way to do it
 
my %players = (
	tendulkar => 102,
	raina     => 34,
	dhoni     => 88,
	harbajan  => 12,
	dravid    => 44,
);

print "Players sorted by name\n";
foreach my $key ( sort keys %players ) {
	print "$key ===> $players{$key}\n";
}


 
Company : Concurrent Technologies
  • Asked To : Vikram Sagere Krishnamurthy
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you print 3rd, 6th and 9th line and so on from a file?
Here is one way to do it
 
while(<DATA>){
	print unless ($. % 3);	
}
__DATA__
Those who say it can't be done are usually interrupted by others doing it.
Do not wish to be anything but what you are, and try to be that perfectly.
It's your attitude and not your aptitude that determines your altitude.
Life is not so much a matter of position as of disposition.
A smile is an inexpensive way to change your looks.
Failure is the path of least persistence.
The pursuit of happiness is the chase of a life time.
The future is purchased by the present.
One thing you can't recycle is wasted time.
Lost time is never found again.
Children need more models than critics.
People don't fail, they give up.
A friend walks in when everyone else walks out.
The happiness of your life depends on the quality of your thoughts.
The more I know, the more I know I don't know.
One good thing about being wrong is the joy it brings others.
To err is human, to blame it on someone else is more human.
When you are arguing with an idiot, make sure the other person isn't doing the same thing.
Minds are like parachutes-they only function when open.
You can't direct the wind, but you can adjust the sail.
Sometimes the best way to figure out who you are is to get to that place where you don't have to be anything else.
Don't confuse me with facts, I prefer to remain ignorant.
If you are never scared, embarrassed of hurt, it means you never take chances.
Humans are like tea bags. They never realize their strength until they are put in hot water.
When you remain true to your beliefs, loyal to your ideas and faithful to your dreams, you remain free forever.
What lies behind us, and what lies before us are tiny matters compared to what lies within us.
We live in a society where pizza get to your house before the police.
Some people tink holding on makes them strong, sometimes its letting go.
Blowing out another man's flame doesn't make your shine any brighter, but less.
The secret of true greatness is simplicity.
Better to understand little than to misunderstand a lot. 


 
Company : Nokia
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you list all duplicates from an array?
Here is one way to do it
 
use strict;
use warnings;

my @nums = qw (one two five one two three two six three four two six eight eight nine);
my @duplicates = ();

foreach my $item (@nums) {
  #grep in scalar context returns how many times $item is found in the @my_array
  my $count = grep $item eq $_, @nums;

  #Add to array '@duplicates' only if $count is greater than 1.
  push @duplicates, $item if $count > 1;
}

#print the duplicate items
print join ',', @duplicates;


 
Company : Nokia
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : What is the difference between Package, Module and Library in the context of Perl?

Library : Generally, a collection of procedures. In ancient days, referred to a collection of subroutines in a .pl file. In modern times, refers more often to the entire collection of Perl modules on your system.

Module : A file that defines a package of (almost) the same name, which can either export symbols or function as an object class. (A module's main .pm file may also load in other files in support of the module.)

Package : A namespace for global variables, subroutines, and the like, such that they can be kept separate from like-named symbols in other namespaces. In a sense, only the package is global, since the symbols in the package's symbol table are only accessible from code compiled outside the package by naming the package. But in another sense, all package symbols are also globals--they're just well-organized globals.


 
Company : Nokia
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : Explain various file open modes in Perl?

The following modes are valid for all forms of open:

Mode Description
< Input only. This is the default when the mode is empty.
> Output only. The file is created or truncated if necessary.
>> Open the file in append mode. The file is created if necessary.
+< Read/write update access.
+> Write/read update access.
+>> Read/append access.

 
Company : Nokia
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : Explain various constants related to seek?

Constants related to seek must be imported explictly by specifying :seek in the import list of Fcntl.

Value Name Description
00 SEEK_SET Seek position.
01 SEEK_CUR Seek offset from current position.
02 SEEK_END Seek offset from end of file.

 
Company : Nokia
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : Explain various constants related to flock?

Constants related to flock must be imported explictly by specifying :flock in the import list of Fcntl.

Value Name Description
001 LOCK_SH Shared lock.
002 LOCK_EX Exclusive lock.
004 LOCK_NB Nonblocking lock.
010 LOCK_UN unlock.

 
Company : Wipro Technologies
  • Asked To : Anand Seshadri
  • Solution Provided by : Shaji Kalidasan
  • Question : What is the difference between @EXPORT and @EXPORT_OK?
When someone uses your module, the Exporter::import() function is called. It uses your module name and finds the @EXPORT, @EXPORT_OK, and %EXPORT_TAGS package variables to determine what functions can be exported. Only function names in @EXPORT_OK and @EXPORT can be exported, but using @EXPORT is usually not recommended because @EXPORT exports all the functions listed in the array, and the programmer using your module no longer has control over what is imported into their namespace.

 
Company : Wipro Technologies
  • Asked To : Anand Seshadri
  • Solution Provided by : Shaji Kalidasan
  • Question : How to separate digits from a number (Integer)?
Here is one way to do it
 
use strict;
use warnings;

print "Please give a number : ";
chomp( my $number = <STDIN> );
my @nums = ();
while ( $number != 0 ) {
	my $remainder = $number % 10;
	unshift @nums, $remainder;
	$number = int( $number / 10 );
}

print join '  ', @nums;


 
Company : Mindtree
  • Asked To : Anand Seshadri
  • Solution Provided by : Shaji Kalidasan
  • Question : How to print the following triangle?
*
**
***
****
*****
******
*******
********
*********
**********

 
Here is one way to do it
 
use strict;
use warnings;
use diagnostics;

print "Enter the number of rows to print : ";
chomp( my $n = <STDIN> );
for ( my $i = 1 ; $i <= $n ; $i++ ) {
	for ( my $j = 1 ; $j <= $i ; $j++ ) {
		print "*";
	}
	print "\n";
}


 
Company : Mindtree
  • Asked To : Anand Seshadri
  • Solution Provided by : Shaji Kalidasan
  • Question : How to print the following triangle?
         *
        **
       ***
      ****
     *****
    ******
   *******
  ********
 *********
**********

 
Here is one way to do it
 
use strict;
use warnings;
use diagnostics;

print "Enter the number of rows to print : ";
chomp( my $n = <STDIN> );
for ( my $i = 1 ; $i <= $n ; $i++ ) {
	for ( my $j = $n ; $j > $i ; $j-- ) {
		print ' ';
	}
	for ( my $k = $i ; $k >= 1 ; $k-- ) {
		print "*";
	}
	print "\n";
}


 
Company : Mindtree
  • Asked To : Anand Seshadri
  • Solution Provided by : Shaji Kalidasan
  • Question : How to print the following triangle?
**********
*********
********
*******
******
*****
****
***
**
*

 
Here is one way to do it
 
use strict;
use warnings;
use diagnostics;

print "Enter the number of rows to print : ";
chomp( my $n = <STDIN> );
for ( my $i = 1 ; $i <= $n ; $i++ ) {
	for ( my $j = $i ; $j <= $n ; $j++ ) {
		print '*';
	}
	print "\n";
}


 
Company : Mindtree
  • Asked To : Anand Seshadri
  • Solution Provided by : Shaji Kalidasan
  • Question : How to print the following triangle?
**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

 
Here is one way to do it
 
use strict;
use warnings;
use diagnostics;

print "Enter the number of rows to print : ";
chomp( my $n = <STDIN> );
for ( my $i = $n ; $i >= 1 ; $i-- ) {
	for ( my $j = $i ; $j < $n ; $j++ ) {
		print ' ';
	}
	for ( my $k = $i ; $k >= 1 ; $k-- ) {
		print '*';
	}
	print "\n";
}


 
Company : Accenture
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you convert a data structure to XML?

 
Here is one way to do it
 
use strict;
use warnings;

use XML::Simple qw(XMLout);

my $data_structure = {
	book => [
		{
			id      => 1,
			title   => ["Programming Perl"],
			author  => ["Larry Wall"],
			edition => [4]
		},
		{
			id      => 2,
			title   => ["Advanced Perl Programming"],
			author  => ["Simon Cozens"],
			edition => [1]
		},
		{
			id      => 3,
			title   => ["Learning Perl"],
			author  => ["Randal Schwartz"],
			edition => [6]
		}
	]
};

print XMLout( $data_structure, RootName => 'books' );


 
Company : Accenture
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you list all files in your home directory (for both Windows and Unix)?
Here is one way to do it
 
use strict;
use warnings;

# $ENV{HOME} stores the home directory on Unix platforms, use
# $ENV{HOMEPATH} for MS Windows

my $home = $ENV{HOME} || $ENV{HOMEPATH};

opendir( my $home_dir, $home ) or die "Can't read dir $home: $!";
while ( my $file = readdir $home_dir ) {

	# Skip over directories and non-plain files (eg devices)
	next unless -f "$home/$file";
	# Do something with $file
	print "$file\n";	
}

closedir $home_dir;
    

 
Company : Accenture
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : What is a closure?

A subroutine that has access to, and preserves the values of, all lexical variables in the scope in which it is defined, even when subsequently called from outside that scope. In Perl, any anonymous subroutine has access to all lexical variables from the scope in which it is defined. Thus, all Perl anonymous subroutines are potentially closures, although only those which do refer to external lexical variables are actually closures.



 
Company : Accenture
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : Can you explain about the special subroutines in Perl?

Special subroutines are user defined, but are called by Perl while processing the program. They can be used to change the order in which parts of a program are executed.

[ sub ] AUTOLOAD block
The code in block is executed when the program calls an undefined subroutine. $AUTOLOAD contains the name of the called subroutine, and @_ contains the parameters.

[ sub ] BEGIN block
The code in block is executed immediately when compilation of the block is complete.

[ sub ] CHECK block
Executed (in reverse order) when the compilation of the program finishes.

[ sub ] END block
Executed in reverse order when the Perl interpreter terminates. Inside the END blocks, $? contains the status with which the program is going to exit.

[ sub ] INIT block
Executed immediately before the Perl interpreter starts executing the program.

[ sub ] UNITCHECK block
Executed (in reverse order) when the compilation of the program unit finishes.



 
Company : Accenture
  • Asked To : Balaji Manikandan
  • Solution Provided by : Shaji Kalidasan
  • Question : What is the use of ~ and ~~ in formatting?

Use ~ in a picture line to suppress unwanted empty lines.

Use ~~ in a picture line to have this format line repeated until it would yield a completely blank line. Use with ^ fields to have them repeated until exhausted.



 
Company : India Bulls
  • Asked To : Sandeep Patidar
  • Solution Provided by : Shaji Kalidasan
  • Question : How can I retrieve only the seconds which is in HH:MM:SS format from a file?

use strict;
use warnings;

open my $fin, '<', 'log.txt' or die "Cannot open file ($!)";

while (<$fin>) {
    #Hour, Minute, Second (Using non capturing parenthesis for Hour and Minute)
    my ($second)  = /(?:\d\d):(?:\d\d):(\d\d)/;
    print "Seconds : $second\n";
}

close $fin;



 
Company : Smart Play
  • Asked To : Sandeep Patidar
  • Solution Provided by : Shaji Kalidasan
  • Question : How can you count the number of negative numbers in the string?

use strict;
use warnings;

my $str = "98 -124 33 45 -119 -28 5678 234 66 -123 4567 -1";

my $count = 0;

while($str =~ /-\d+/g) {
	$count++;
}

print "The number of negative numbers in the string is : $count\n";



 
Company : Smart Play
  • Asked To : Sandeep Patidar
  • Solution Provided by : Shaji Kalidasan
  • Question : How can you count the number of characters in a string?

use strict;
use warnings;

my $str = "Father's goodness is higher than the mountain and mother's goodness is deeper than the sea.";

my $count = $str =~ tr/e/e/; #Counting the number of 'e's

print "Number of 'e's in this string is $count\n";



 
Company : Smart Play
  • Asked To : Sandeep Patidar
  • Solution Provided by : Shaji Kalidasan
  • Question : How can you concatenate two strings?

use strict;
use warnings;

my $str1 = "Hello";
my $str2 = "World";

my $str = $str1 . ' ' . $str2;

print "The string is $str";



 
Company : Tata Elxsi
  • Asked To : Sandeep Patidar
  • Solution Provided by : Shaji Kalidasan
  • Question : How can you get unique elements from multiple arrays?

#Get unique elements from multiple arrays

use strict; 
use warnings; 
 
my @array1 = (10,20,30); 
my @array2 = (11,22,33); 
my @array3 = (10,20,30);
my @array4 = (45,10,98); 

my %unique; # Hash to hold unique elements

$unique{$_} ++ for (@array4, @array2, @array1, @array3);
 
print join ',', sort keys %unique;



 
Company : Tata Elxsi
  • Asked To : Sandeep Patidar
  • Solution Provided by : Shaji Kalidasan
  • Question : How can you replace the nth occurence of the string in a case insensitive manner with the text 'PERL'?

use strict; 
use warnings; 

my $count = 0;
my $nth_occurence = 3; 

open my $fin, '<', 'data1.txt' or die "Cannot open file ($!)";
while (<$fin>) {
	if(/perl/ig) {
		$count++;
		s/perl/PERL/i if $count == $nth_occurence;		
	}
	print;
}

close $fin;



 
Company : Tata Elxsi
  • Asked To : Sandeep Patidar
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you count the number of lines, words and characters from a file?

use strict;
use warnings;

my $filename = 'data.txt';
open my $fin, '<', $filename or die "Could not open file: ($!)";

my ($lines, $words, $chars);

while (<$fin>) {
    $lines++;
    $chars += length;
    $words += scalar(split /\s+/, $_);
}

print "Number of lines : $lines\n";
print "Number of words : $words\n";
print "Number of characters : $chars\n";



 
Company : Tata Elxsi
  • Asked To : Sandeep Patidar
  • Solution Provided by : Shaji Kalidasan
  • Question : How do you validate an IP address and print whether it is valid or not?

use strict;
use warnings;

while(<DATA>) {
   chomp;
   # Check only for standalone IP address not the embedded one
   if(/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/) {
       print "$_ is a valid ip address\n";
   } else {
   	   print "$_ is an invalid ip address\n";
   }   
}

__DATA__
192.168.999.34
192.168.2.3
876.768.22.3
192.255.255.0
255.0.0.0
128.0.128.255
255.255.255.255
0.0.0.0
Winds are blowing with velocity 124.25 miles per hour
Please check the balance123.78.23.45amount



 
Company : Kodiak Networks
  • Asked To : Sandeep Patidar
  • Solution Provided by : Shaji Kalidasan
  • Question : Check the number of arguments passed (in this case three) and validate whether it exists in the hash?

use strict;
use warnings;

#Hash representing the country and the rank (global position)
my %nation = (
      Australia => '12',
      USA => 1,
      UK => 4,
      Japan => 3,
      China => 2,
      India => 5
);

sub display {
	print '-' x 60, "\n";
	# The special array @_ contains the arguments passed to this subroutine
	if(@_ != 3) {
		print "Incorrect number of arguments : You must pass exactly three arguments\n";
		print "The arguments passed were => (", join (',', @_), ")\n";
	}
	
	foreach my $country (@_) {
		if(exists $nation{$country}) {
			print "$country exists in the hash\n";
		} else {
			print "$country does not exists in the hash\n";
		}
	}
	print '-' x 60, "\n";
}

display ('Australia', 'India', 'China'); #No error
display ('USA', 'UK'); #Error : Incorrect arguments
display ('India', 'USA', 'China', 'Japan', 'UK'); #Error : Incorrect arguments



 
Company : Juniper Networks
  • Asked To : Mohanasundaram
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you limit your application to a specific Perl version?

use strict;
use warnings;

BEGIN {
	die "This is Perl $], but you need 5.010000" unless $] == 5.010000; #Checks for Perl version 5.10
}



 
Company : Juniper Networks
  • Asked To : Mohanasundaram
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you check for the right operating system?

use strict;
use warnings;

BEGIN {
	die "Unsupported OS: You have $^O but this application requires Windows!" unless $^O eq 'MSWin32'; #Checks for Windows
}



 
Company : Juniper Networks
  • Asked To : Mohanasundaram
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you avoid unnecessary backtracking?

use strict;
use warnings;

#Note: As of Perl 5.10, the regular expression engine automatically modifies each string-literal 
#alternations into a trie, so in some cases you don't have to handle the details yourself.

use Regexp::Trie;

my $rt = Regexp::Trie->new;
foreach (qw/suntan sunbeam sunrays sunlight/) {
	$rt->add($_);
}

my $alternation = $rt->regexp;
print $alternation; # prints ---> (?^:sun(?:beam|light|rays|tan))

my $string = "The sunrays strike the room at 7 AM everyday";

if($string =~ m/$alternation/) {
	print "\nMatch";
} else {
	print "\nNot a match";
}



 
Company : Juniper Networks
  • Asked To : Mohanasundaram
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you print the last ten lines from a file backward?

use strict;
use warnings;

open my $fin, '<', 'data.txt' or die "Cannot open file for read ($!)";
chomp(my @lines = <$fin>);
close $fin;

for(my $i = 1; $i <= 10; $i++) {
	my $line = pop @lines;
	print "$line\n";
}



 
Company : Juniper Networks
  • Asked To : Mohanasundaram
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you compare two files?

use strict;
use warnings;

use File::Compare; #Using standard File::Compare module

my $file1 = 'data1.txt';
my $file2 = 'data2.txt';

if(compare($file1, $file2) == 0) {
	print 'The files are equal';
} else {
	print 'The files are not equal';
}



 
Company : Juniper Networks
  • Asked To : Mohanasundaram
  • Solution Provided by : Shaji Kalidasan
  • Question : How will you merge two hashes?

use strict;
use warnings;

#Players and their highest scores in ODI
my %team_india = (
                   dhoni => '183*',
                   tendulkar => '200*',
                   sehwag => '219',
                   yuvraj => '139',
                   kohli => '183'
                 );
                 
my %team_westindies = (
                   richards => '189*',
                   walsh => '30',
                   ambrose => '31*',
                   lara => '169'
                 );    
                 
my %squad = (%team_india, %team_westindies);

while (my ($key, $value) = each %squad) {
	print "$key : $value\n";
}