You are on page 1of 13

www.sybaserays.

com Perl
Interview Questions
1 of 13







Perl
Interview Questions and Answers


Prepared by Abhisek Vyas
Document Version 1.0
Team, www.sybaserays.com








www.sybaserays.com Perl
Interview Questions


Q. How do you separate executable statements in perl?
A. semi-colons separate executable statements
Example:
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

Example:
if( defined $opts{'f'} ) {
$Force_Rerun = $opts{'f'};
} else {
$Force_Rerun = "N";
}

Q. What do you mean by a shebang?
A. To tell the OS that perl should execute the following code
Example:
#!/usr/bin/perl

Note: MUST be first line of the file.. no comments, no spaces prior to the shebang
Standard: #!/usr/bin/perl

Q. How to make perl files self executable?
A. Can make perl files self executable by making first line as #! /bin/perl.
The extension tells the kernel that the script is a perl script and the first line tells it where to look for
perl.

Q. What is the use of the -w switch in perl?
A. The -w switch tells perl to produce extra warning messages about potentially dangerous constructs.

Q. Do we have to compile create object file and then execute it?
A. The advantage of Perl is that you dont have to compile create object file and then execute.

Note: The pound sign "#" is the symbol for comment entry. There is no multiline comment entry , so
you have to use repeated # for each line.

Q. What is the use of print command?
A. The "print command" is used to write outputs on the screen.
Example:
Print "Hello World";
Prints "Hello World" on the screen. It is very similar to printf statement in C.
www.sybaserays.com Perl
Interview Questions
3 of 13
Q. What is the use of printf command?
A. If you want to use formats for printing you can use printf.

IMPORTANT NOTES:
Quoting Strings:
With ' (apostrophe): Everything is interpreted literally
Single quotation marks are used to enclose data you want taken literally. Just as the <code></code>
tags here at the Monastery make all text they enclose literally rendered, whitespace and all, so too
does a set of single-quotes in Perl ensure that what they enclose is used literally:

#!/usr/bin/perl -w
use strict;
my $foo;
my $bar;
$foo = 7;
$bar = 'it is worth $foo';
print $bar;

This example, when run, produces the following:
it is worth $foo

With " (double quotes): Variables get expanded
Double quotation marks are used to enclose data that needs to be interpolated before processing.
That means that escaped characters and variables aren't simply literally inserted into later operations,
but are evaluated on the spot. Escape characters can be used to insert newlines, tabs, and other
special characters into a string, for instance. The values, or contents, of variables are used in double-
quoted strings, rather than the names of variables. For instance:

#!/usr/bin/perl -w
use strict;
my $foo;
my $bar;
$foo = 7;
$bar = "it is worth $foo";
print $bar;

This example, when run, produces the following:
it is worth 7

Note: Double-quotes interpolate scalar and array variables, but not hashes. On the other hand, you
can use double-quotes to interpolate slices of both arrays and hashes.

With ` (backtick):
The text is executed as a separate process, and the output of the command is returned as the value of
the string
Quote
quoting without quotes:
www.sybaserays.com Perl
Interview Questions


In Perl, you can use methods other than quotation marks to "quote" a string. This functionality makes
using strings that contain quotation marks much easier sometimes, since those quotation marks no
longer need to be escaped. There are three simple methods of doing this with the letter q.
q - singly quote a string :
The first way to quote without quotes is to use q() notation. Instead of using quotation marks, you
would use parentheses with a q preceding them:
#!/usr/bin/perl -w
use strict;
my $foo;
my $bar;
$foo = 7;
$bar = q(it is 'worth' $foo);
print $bar;

This example, when run, produces the following:

it is 'worth' $foo

qq - doubly quote a string :
In the same way that double-quotes add interpolation to the functionality of single-quotes, doubling
the q adds interpolation to quoting without quotation marks. For instance, if you wanted to avoid
escape characters and interpolate $foo in the above code, and wanted to use double-quotes around
the word worth, you might do this:
#!/usr/bin/perl -w
use strict;
my $foo;
my $bar;
$foo = 7;
$bar = qq(it is "worth" $foo);
print $bar;

This example, when run, produces the following:

it is "worth" 7

qw - quote a list of words:
You can use qw to quote individual words without interpolation. Use whitespace to separate terms
you would otherwise have to separate by quoting individually and adding commas. This is often quite
useful when assigning lists to array variables. The two following statements are equivalent:

@var = ('One','Two', 'Three');
@var1 = qw(One Two Three);
print "@var \n";
print "@var1 \n";

It will print 2 lines:
One Two Three
One Two Three

www.sybaserays.com Perl
Interview Questions
5 of 13

quotemeta - quote regular expression magic characters
qx - backquote quote a string

Q. What are the data types available in Perl language?
A. Three data types are available in the Perl language:
Scalars
Arrays
hashes

Q What is scalar variable?
A. A scalar, which represents the fundamental type of Perl data, can be a string, a number or a
reference.
They should always be preceded with the $ symbol.
There is no necessity to declare the variable before hand .
There are no datatypes such as character or numeric.
The scalar variable means that it can store only one value.
If you treat the variable as character then it can store a character. If you treat it as string it can
store one word . if you treat it as a number it can store one number.
Example: $name = "betty" -- The value betty is stored in the scalar variable $name.
Default values for all variables is undef.Which is equivalent to null.


Q What are scalar functions?
A. 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


www.sybaserays.com Perl
Interview Questions


Q. What is list variable?
A.
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.
Q. What are array functions?
A.
Array functions:
Grep
Join
Map
Pop
Push
Shift
Unshift
Scalar
Lenghth of an array
Array swapping(Slice)
Splice
Split
Sort
Context

Q. What is perl hash?
A.
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);

www.sybaserays.com Perl
Interview Questions
7 of 13

Functions for Hashes:
Each
Keys
Values
Exists
Delete
Hash length
Sort
Context
Q. Explain control structure in perl?
A.
Control Structures:
If / unless statements : If similar to the if in C.
Eg of unless.
Unless(condition){}.
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.




www.sybaserays.com Perl
Interview Questions



Q. What are the comparison operators in perl?
A.
Comparison Operators:
String Operation Arithmetic
lt less than <
gt greater than >
eq equal to ==
le less than or equal to <=
ge greater than or equal to >=
ne not equal to !=
cmp compare, return 1, 0, -1 <=>

Q. What are the logical operators in perl?
A.
Logical Operators:
Operator Operation
||, or logical or
&&, and logical and
!, not logical not

Q. What are string operators in perl?
A.
String Operators:
Operator Operation
www.sybaserays.com Perl
Interview Questions
9 of 13
. string concatenation
.= concatenation and assignment

Q. How do you declare function and call function in perl?
A.
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] ....



Q. What is regex?
A.
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.
Example:
$mystring=~/blahblah/ ;
Matching Anything
/sh[ou]t/
www.sybaserays.com Perl
Interview Questions


/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]/

Q. What are useful Perl Characters?
A. \n, \w, \W ,\s ,\S ,\d ,\D , \b Match a word boundary ,\B Match a non-(word boundary) ,\A Match
only at beginning of string

Q. Obscure Perl special characters?
A. \t ,\r ,\f ,\x1B ,\033 ,\Q ,\L ,\U ,\E ,\Q



www.sybaserays.com Perl
Interview Questions
11 of 13
Q. How to substitute a string?
A. $mystring=~s/Anne/Jim/
s/Anne/Jim/g
s/is/was/ig
Another use for (parenthesis)
/A(dam|nne|ndrew)/

IMPORTANT NOTES:
ANCHORS:
^ Match string start (or line, if /m is used)
$ Match string end (or line, if /m is used) or before newline
\b Match word boundary (between \w and \W)
\B Match except at word boundary (between \w and \w or \W and \W)
\A Match string start (regardless of /m)
\Z Match string end (before optional newline)

QUANTIFIERS
Match 0 or more times (*)
Match 0 or 1 time (?)
Match 1 or more times (+)
Match exactly n times ({n} )
Match at least n times {n,}
Match at least n, but not more than m, times
{n,m}

Greedy and Non-Greedy
Greedy:
my $string = 'bcdabdcbabcd';
$string =~ m/^(.*)ab/;
Non-Greedy:
$string =~ m/^(.*?)ab/;

VARIABLES :
$` Everything prior to matched string
$& Entire matched string
$ Post match
$1, $2 ... hold the Xth captured expr
www.sybaserays.com Perl
Interview Questions


$+ Last parenthesized pattern match
quotemeta Quote metacharacters

File Processing:
Reading (< $file&path)
Writing and overwriting (> $file&path)
Writing and Appending (>> $file&path )
Read and Write only, no file creation/appending. (+<$file&path )
Read, Write, Create, overwrites rather than appending (+>$file&path )
Read, Write, Create, Append, no overwriting. (+>>$file&path )
File Slurping
File Locking
use Fcntl qw(:flock);
open(DAT,"$sitedata") || die("Cannot Open File");
flock(DAT, LOCK_EX);
close(DAT);

FILE VALIDATION:
-e part is the existence test
Readable: -r
Writable: -w
Executable: -x
Text File: -T
Binary File: -B
Entry is a socket : -S
Entry is a directory: -d
Entry is a plain file: -f
Entry is a symbolic link: -l
File exists and has zero size (always false for directories) : -z

Error Handling:
Warn
Die ($!)
Installing CPAN Module:
perl -MCPAN -e shell
install MODULE::NAME
www.sybaserays.com Perl
Interview Questions
13 of 13
Or single line
perl -MCPAN -e 'install HTML::Template'

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

You might also like