You are on page 1of 8

Perl Basic Interview Question and answer

1. How many type of variable in perl


Perl has three built in variable types
Scalar
Array
Hash
2. What is the different between array and hash in perl
Array is an order list of values position by index.
Hash is an unordered list of values position by keys. It is a set key/value pairs.
Arrays are ordered sequences of scalars, and hashes are unordered baskets of scalars
Hash Example:
#!/usr/bin/perl
my %data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
print "\$data{'John Paul'} = $data{'John Paul'}\n";
print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";

This will produce the following result


$data{'John Paul'} = 45
$data{'Lisa'} = 30
$data{'Kumar'} = 40

Hashes can also be used like this

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40); // - can be used instead
of

The values can be extracted/ sliced from the hash table using Arrays
%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
@array = @data{-JohnPaul, -Lisa};
print "Array : @array\n";
Result: Array : 45 30

Getting Hash Size

You can get the size - that is, the number of elements from a hash by using the scalar context on
either keys or values. Simply saying first you have to get an array of either the keys or values and
then you can get the size of array as follows
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size:

is $size\n";

@values = values %data;


$size = @values;
print "2 - Hash size: is $size\n";

This will produce the following result


1 - Hash size: is 3
2 - Hash size: is 3

Add and Remove Elements in Hashes

Adding a new key/value pair can be done with one line of code using simple assignment
operator. But to remove an element from the hash you need to use delete function as shown
below in the example
#!/usr/bin/perl
%data
@keys
$size
print

= ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
= keys %data;
= @keys;
"1 - Hash size: is $size\n";

# adding an element to the hash;


$data{'Ali'} = 55;
@keys = keys %data;
$size = @keys;
print "2 - Hash size: is $size\n";
# delete the same element from the hash;
delete $data{'Ali'};
@keys = keys %data;
$size = @keys;
print "3 - Hash size: is $size\n";

This will produce the following result


1 - Hash size: is 3
2 - Hash size: is 4
3 - Hash size: is 3

3. What is the difference between a list and an array?


A list is a fixed collection of scalars. An array is a variable that holds a variable collection of
scalars.

4. what is the difference between use and require in perl


Use :
1. The method is used only for the modules(only to include .pm type file)
2. The included objects are varified at the time of compilation.
3. No Need to give file extension.
Require:
1. The method is used for both libraries and modules.
2. The included objects are varified at the run time.
3. Need to give file Extension.

5. How to Debug Perl Programs


Start perl manually with the perl command and use the -d switch, followed by your script and
any arguments you wish to pass to your script:
"perl -d myscript.pl arg1 arg2"

6. What is a subroutine?
A subroutine is like a function called upon to execute a task.
subroutine is a reusable piece of code.

7. what does this mean '$^0'? tell briefly


$^ - Holds the name of the default heading format for the default file handle. Normally, it is
equal to the file handle's name with _TOP appended to it.
8. What is the difference between die and exit in perl?
1) die is used to throw an exception
exit is used to exit the process.
2) die will set the error code based on $! or $? if the exception is uncaught.
exit will set the error code based on its argument.
3) die outputs a message
exit does not.

9. How to merge two array?


@a=(1, 2, 3, 4);
@b=(5, 6, 7, 8);
@c=(@a, @b);
print "@c";

10. Adding and Removing Elements in Array


Use the following functions to add/remove and elements:
push(): adds an element to the end of an array.
unshift(): adds an element to the beginning of an array.
pop(): removes the last element of an array.
shift() : removes the first element of an array.

11. How to get the hash size


%ages = ('Martin' => 28, 'Sharon' => 35, 'Rikke' => 29);
print "Hash size: ",scalar keys %ages,"\n";

12. Add & Remove Elements in Hashes


%ages = ('Martin' => 28, 'Sharon' => 35, 'Rikke' => 29);
# Add one more element in the hash
$age{'John'} = 40;
# Remove one element from the hash
delete( $age{'Sharon'} );

13. PERL Conditional Statements


The conditional statements are if and unless

14. Perl supports four main loop types:


While, for, until, foreach

15. There are three loop control keywords: next, last, and redo.
The next keyword skips the remainder of the code block, forcing the loop to proceed to the next
value in the loop.

The last keyword ends the loop entirely, skipping the remaining statements in the code block, as
well as dropping out of the loop.
The redo keyword reexecutes the code block without reevaluating the conditional statement for
the loop.

16. Renaming a file


rename ("/usr/test/file1.txt", "/usr/test/file2.txt" );

17. Deleting an existing file


unlink ("/usr/test/file1.txt");

18. Explain tell Function


The first requirement is to find your position within a file, which you do using the tell function:
tell FILEHANDLE
tell

19. Perl Regular Expression


A regular expression is a string of characters that define the pattern
There are three regular expression operators within Perl
Match Regular Expression - m//
Substitute Regular Expression - s///
Transliterate Regular Expression - tr///
20. What is the difference between chop & chomp functions in perl?
chop is used remove last character, chomp function removes only line endings.
21. Email address validation perl
if ($email_address =~ /^(\w\-\_\.)+\@((\w\-\_)+\.)+[a-zA-Z]{2,}$/)
{
print "$email_address is valid";
}
else {
print "$email_address is invalid";
}

22. Why we use Perl?


1.Perl is a powerful free interpreter.
2.Perl is portable, flexible and easy to learn.
23. Given a file, count the word occurrence (case insensitive)
open(FILE,"filename");
@array= ;
$wor="word to be found";
$count=0;
foreach $line (@array)
{
@arr=split (/s+/,$line);
foreach $word (@arr)
{
if ($word =~ /s*$wors*/i)
$count=$count+1;
}
}
print "The word occurs $count times";
23. Name all the prefix dereferencer in perl?
The symbol that starts all scalar variables is called a prefix dereferencer. The different types of
dereferencer are.
(i) $-Scalar variables
(ii) %-Hash variables
(iii) @-arrays
(iv) &-subroutines
(v) Type globs-*myvar stands for @myvar, %myvar.
24. What is the Use of Symbolic Reference in PERL?
$name = "bam";
$$name = 1; # Sets $bam
${$name} = 2; # Sets $bam
${$name x 2} = 3; # Sets $bambam
$name->[0] = 4; # Sets $bam[0]
symbolic reference means using a string as a reference.
25. What is the difference between for & foreach, exec & system?
Both Perl's exec() function and system() function execute a system shell command. The big
difference is that system() creates a fork process and waits to see if the command succeeds or
fails - returning a value. exec() does not return anything, it simply executes the command.
Neither of these commands should be used to capture the output of a system call. If your goal is
to capture output, you should use the $result = system(PROGRAM); exec(PROGRAM);

26. What is the difference between for & foreach?


Technically, there's no difference between for and foreach other than some style issues. One is
an lias of another. You can do things like this foreach (my $i = 0; $i < 3; ++$i)
{ # normally this is
foreach print $i, "n";
}
for my $i (0 .. 2)
{ # normally this is for print $i, "n";}
27. What is eval in perl?
eval(EXPR)
eval EXPR
eval BLOCK
EXPR is parsed and executed as if it were a little perl program. It is executed in the context of
the current perl program, so that any variable settings, subroutine or format definitions remain
afterwards. The value returned is the value of the last expression evaluated, just as with
subroutines. If there is a syntax error or runtime error, or a die statement is executed, an
undefined value is returned by eval, and $@ is set to the error message. If there was no error, $@
is guaranteed to be a null string. If EXPR is omitted, evaluates $_. The final semicolon, if any,
may be omitted from the expression.

28. What's the difference between grep and map in Perl?


grep returns those elements of the original list that match the expression, while map returns the
result of the expression applied to each element of the original list.
29. How to Connect with SqlServer from perl and how to display database table info?
there is a module in perl named DBI - Database independent interface which will be used to
connect to any database by using same code. Along with DBI we should use database specific
module here it is SQL server. for MSaccess it is DBD::ODBC, for MySQL it is DBD::mysql
driver, for integrating oracle with perl use DBD::oracle driver is used. IIy for SQL server there
are avilabale many custom defined ppm( perl package manager) like Win32::ODBC,
mssql::oleDB etc.so, together with DBI, mssql::oleDB we can access SQL server database from
perl. the commands to access database is same for any database.
30. Remove Duplicate Lines from a File
use strict;
use warnings;
my @array=qw(one two three four five six one two six);
print join(" ", uniq(@array)), "\n";
sub uniq {

my %seen = ();
my @r = ();
foreach my $a (@_) {
unless ($seen{$a}) {
push @r, $a;
$seen{$a} = 1;
}
}
return @r;
}
or
my %unique = ();
foreach my $item (@array)
{
$unique{$item} ++;
}
my @myuniquearray = keys %unique;
print "@myuniquearray";

You might also like