Saturday, January 26, 2013

perl interview questions and answers

1.     What is CPAN? Its uses?
CPAN (Comprehensive Perl Archive Network) is a large collection of free Perl software and documentation
CPAN is also name of the module, which is used to download and install module from the archive.
2.     What does “use strict” , “use vars” , “no vars” mean?
#!/usr/local/bin/perl -w
use strict;
1. This will help you (really, it will force you) to write better, cleaner code.
Adding the -w switch to the perl interpreter will cause it to spit out warnings on uninitialized variables - potential bugs.
'use strict' turns on the 'strict' pragma which will make you declare your variables with the my keyword.
'use strict' also tosses up errors if your code contains any barewords that can't be interpreted in their current context. 

2. vars - Perl pragma to predeclare global variable names (obsolete)

3. no vars - You may not rescind such declarations with no var.
 
3.     Difference b/w use and require?
1. use only expects a bareword, require can take a bareword or an expression
2. use is evaluated at compile-time, require at run-time
3. The "require" it there where you want to use it but don't "use" it(i.e. Use: can't be called with parens, can't be used in an expression, etc).

example :

  • Use DBI;
  • require "siva.pm";


4.     What do the symbols $ @ and % mean when prefixing a variable?
1. $a : means it is a variable.
2. @a : means it is an array.
3.  %a : means it is a hash.
5.     What purpose does each of the following serve: -w, strict, -T ?
#!/usr/local/bin/perl -w
use strict;
This will help you (really, it will force you) to write better, cleaner code.
Adding the -w switch to the perl interpreter will cause it to spit out warnings on uninitialized variables - potential bugs.
'use strict' turns on the 'strict' pragma which will make you declare your variables with the my keyword.
'use strict' also tosses up errors if your code contains any barewords that can't be interpreted in their current context.
-T:
Taint mode is a way of making your code more secure. It means that your program will be fussier about data it receives from an external source. External sources include users, the file system, the environment, locale information, other programs and some system calls (e.g. readdir).
There are differing opinions on when to use taint mode. Certainly as a minimum, any CGI application should use taint mode. When accepting external data you should always program defensively and use taint mode to ensure that the external data matches your expectations
6.     Explain the use of do, require, use, import
do will call the code, no ifs, ands, or buts, at runtime. This is usually a bad idea, because if that's happening, you should really probably be putting it into a subroutine.
While do() behaves almost identically to require(), it reloads the file unconditionally. It doesn't check %INC to see whether the file was already loaded. If do() cannot read the file, it returns undef and sets $! to report the error. If do() can read the file but cannot compile it, it returns undef and puts an error message in $@. If the file is successfully compiled, do() returns the value of the last expression evaluated.
---------------------
Require: will call exactly once and then no more, at runtime. it can do it for a package, too, in which case it will actually go find that package for you.
require() reads a file containing Perl code and compiles it. Before attempting to load the file it looks up the argument in %INC to see whether it has already been loaded. If it has, require() just returns without doing a thing. Otherwise an attempt will be made to load and compile the file.
require() has to find the file it has to load. If the argument is a full path to the file, it just tries to read it. For example:
require "/home/httpd/perl/mylibs.pl";
use does everything require does in the package case, then calls import in that package.
use(), just like require(), loads and compiles files containing Perl code, but it works with modules only and is executed at compile time.
The only way to pass a module to load is by its module name and not its filename. If the module is located in MyCode.pm, the correct way to use() it is: use MyCode
-------------------------------------------------
import is a function defined in a package. it gets called by use, but it's not otherwise special.
7.     Use of our, my and local?
My: non-package variables, private variable, So that the variable cannot be accessed in the form of $package_name::variable.
Our: package variables, global variables, they can be accessed outside the package (or lexical scope) with the qualified namespace, as $package_name::variable.
Local: A local modifies its listed variables to be "local" to the enclosing block, eval, or do FILE --and to any subroutine called from within that block
8.     Use of ref function
REF is just a reference to another reference.
9.     What are STDIN,STDOUT and STDERR?.
STDIN - Standard Input, for user control input, typically the keyboard
STDOUT - Standard Output,for regular use output, typically the screen
STDERR - Standard Error, for error output; typically defaults to the screen too
DATA - Input for data stored after __END__ at the end of the program
10.   @INC and %INC
The @INC array holds all the file system paths where Perl will be looking for modules when you use or require them. After use or require,
The %INC hash will contain the loaded modules and where they were loaded from.
Examples from my laptop:
@INC:
'/etc/perl',
'/usr/local/lib/perl/5.10.0',
'/usr/local/share/perl/5.10.0',
'/usr/lib/perl5',
'/usr/share/perl5',
'/usr/lib/perl/5.10',
'/usr/share/perl/5.10',
'/usr/local/lib/site_perl',
%INC:
'warnings/register.pm' => '/usr/share/perl/5.10/warnings/register.pm',
'bytes.pm' => '/usr/share/perl/5.10/bytes.pm',
'XSLoader.pm' => '/usr/lib/perl/5.10/XSLoader.pm',
'Carp.pm' => '/usr/share/perl/5.10/Carp.pm',
'Exporter.pm' => '/usr/share/perl/5.10/Exporter.pm',
'warnings.pm' => '/usr/share/perl/5.10/warnings.pm',
'overload.pm' => '/usr/share/perl/5.10/overload.pm',
'Data/Dumper.pm' => '/usr/lib/perl/5.10/Data/Dumper.pm'
(%INC contains Data::Dumper because I used it to quickly dump those two values).


11.   How you can invoke shell command? Hint: system(), backtick, exec() in details
Exec executes a command and never returns. It's like a return statement in a function. If the command is not found exec returns false. It never returns true, because if the command is found it never returns at all. There is also no point in returning STDOUT, STDERR or exit status of the command
System executes a command and your Perl script is continued after the command has finished. The return value is the exit status of the command.
backticks like system executes a command and your perl script is continued after the command has finished.
12.   What is the exact difference between system() and exec() (similar to question no 11)
13.   Error handling using eval
you can use the eval() function to trap the error and avoid ending the script. The eval() function accepts an expression and then executes it. Any errors generated by the execution will be isolated and not affect the main program. However, all function definitions and variable modifications do affect the main program.
Example: Using the eval() Function
You can use the eval() function to trap a normally fatal error:
eval { alarm(15) };
warn() if $@;

eval { print("The print function worked.\n"); };
warn() if $@;


This program displays the following:

The Unsupported function alarm function is unimplemented at test.pl line
2        ...caught at test.pl line
3. The print function worked.
14.   Print the array @arr in reversed case-insensitive order .
#! /bin/perl
@array = ("b","f","n","m");
@array = ( reverse ( sort(@array) ) );
print "@array" ;
15.   There are two types of eval statements i.e. eval EXPR and eval BLOCK. Explain them.
 
eval BLOCK is used to catch exception. It's called try in other languages. It's perfectly safe.
eval EXPR is used to compile and execute code. While it does catch exceptions, that's not it's main purpose. It should be avoided as much as possible, and its use should raise big warning flags.
16.   Autoverification (very rarely)
17.   Questions on hash and hash reference
my %hash = (1 => 'compile', 2 => 'binary',
            3 => 'ascii',   4 => 'digit');

# print the hash ordered pairs
foreach (sort {$hash{$b} cmp $hash{$a}} keys %hash) {
  print "$_: $hash{$_}\n";
}
b.     Length of a hash
%time = (hour => 12, min =>25, sec => 32, msec =>75);
$size = scalar keys %time;   # explicit scalar context - or
$size = keys %time;   # implicit scalar context - or

$timeRef = \%time;    # using a reference
$size = keys %$timeRef;  

print "Hash size: $size\n";  # prints Hash size: 4
c.     How to refer a hash and how to dereference it
Similar to the array, Perl hash can also be referenced by placing the ‘\’ character in front of the hash. The general form of referencing a hash is shown below.

  %author = (
'name'              => "Harsha",
'designation'      => "Manager"
);
$hash_ref = \%author;
This can be de-referenced to access the values as shown below.
$name = $ { $hash_ref} { name };
d.     Nesting of hash
A multidimensional hash is the most flexible of Perl's nested structures. It's like building up a record that itself contains other records.
%HoH = (
    flintstones => {
        husband   => "fred",
        pal       => "barney",
    },
    jetsons => {
        husband   => "george",
        wife      => "jane",
        "his boy" => "elroy",  # Key quotes needed.
    },
    simpsons => {
        husband   => "homer",
        wife      => "marge",
        kid       => "bart",
    },
);
18.   Chomp and chop
Chop: removes from argument last character of string.
Chomp: removes from argument last character of string if it is return.
19.   Explain qw,qq,qx (what’s its use, when to use)
qw: Quote-like operator. Takes a string as parameter and builds a quoted list. @array = qw{red blue yellow};
20.   What are the different ways to concatenate strings in Perl

Using ${name}

$name = 'foo';
$filename = "/tmp/${name}.tmp";

using Perl's dot operator

$name = checkbook';
$filename = '/tmp/' . $name . '.tmp';

# $filename now contains "/tmp/checkbook.tmp"

using Perl's join function

$name = 'checkbook';
$filename = join '', '/tmp/', $name, '.tmp';

# $filename now contains "/tmp/checkbook.tmp"


21.   Functions on array: Push, pop, shift, unshift, join, split, splice
Push: push (ARRAY, LIST)-  adds LIST to the end of a given array, and returns the new number of elements in the array.
 POP: pop (ARRAY) Perl pop function is used to remove and return the last element of an array.
 Shift: Perl shift function removes and returns the first element of an array, shortening the dimension of the array with 1.
 Unshift: The Perl unshift function inserts a list at the beginning of an array and returns the number of elements of the array after the insertion.
 Join: Perl join function is used to concatenate the elements of an array.
 Split: Perl split function allows you to break up a string into an array or a list, by using a specific pattern.
 Splice: The Perl splice function is for arrays and is used to remove, replace or add elements.
 
22.   Different hash functions like each, keys, values, exists, delete
 

removes a key-value pair from a hash; you can delete an individual element of a hash or a hash slice.
returns a two-element list that contains a (key, value) pair from a hash or a (index, value) pair from an array
it checks whether a particular hash/array element or a subroutine exists
use this function to get the indices of an array or the keys of a hash
use this function to get the values of an array or a hash
Sort of Hash by hash value:
# define a hash
my %hash = (1 => 'compile', 2 => 'binary',
            3 => 'ascii',   4 => 'digit');

# print the hash ordered pairs
foreach (sort {$hash{$b} cmp $hash{$a}} keys %hash) {
  print "$_: $hash{$_}\n";
}
24.   How to set Environment variables in Perl (Hint: %ENV)
$ENV{'HOME'} = '/path/to/new/home';
25.   Use of map and grep functions in Perl
Map : The Perl map function evaluates a block or an expression for each element of an array and returns a new array with the result of the evaluation
Grep: Perl grep function is used to filter a list and to return only those elements that match a certain criteria - in other words it filters out the elements which don’t match a condition. Normally, the function will return a list that contains less elements then the original list
26.  What is the difference between die and exit in perl
1) die is used to throw an exception (catchable using eval). 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.
27.   Array with repeating digits. Sort and print digits with no of counts. Ex: @arr = (1,2,4,6,3,1,2,6,8,3,4,9,1,2,4). Output should be @arr = (1,1,1,2,2,2,3,3,4,4,4,6,6,8,9) ). You can’t use hash feature. Think about optimization too.
28.   Decimal to binary (program)


$decimalnum = bin2dec($binarynum);

# Convert a binary number to a decimal number
sub bin2dec {
 unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}
29.   How to find which method is being invoked or being called in Perl and in which method you are currently? Hint: caller()


Returns information about the current subroutines caller. In a scalar context, returns the caller's package name or the package name of the caller EXPR steps up.
($package, $filename, $line) = caller;
($package, $filename, $line, $subroutine,$hasargs, $wantarray, $evaltext, $is_require) = caller($i); 
30.   Explain the use of caller and wantarray function?

wantarray
wantarray is a special keyword which returns a flag indicating which context your subroutine has been called in. 

It will return one of three values.

true: If your subroutine has been called in list context
false: If your subroutine has been called in scalar context
undef: If your subroutine has been called in void context

For example:-

You have a subroutine named "display" and from that subroutine sometimes you want to return an array and sometimes a scalar.

So the syntax would be

sub display(){
return(wantarray() ? qw(A B C) : '1');
}

my @ab = display();
my $bd = display();

then output is

#@ab = (A B C);
and 
#$bd = 1;

The output will be depend upon the left hand side
assignment. If you put an array (@ab) it will call 
wantarray() else a scalar value will return.
31.   How will you find line number, package and a file name in Perl? (Hint: __FILE__, __LINE__, __PACKAGE__)
The special literals __FILE__, __LINE__, and __PACKAGE__ represent the current filename, line number, and package name at that point in your program. They may be used only as separate tokens; they will not be interpolated into strings. If there is no current package (due to an empty package; directive), __PACKAGE__ is the undefined value.
The caller function will do what you are looking for:
sub print_info {
   my ($package, $filename, $line) = caller;
   ...
}

print_info(); # prints info about this line
This will get the information from where the sub is called, which is probably what you are looking for. The __FILE__ and __LINE__ directives only apply to where they are written, so you can not encapsulate their effect in a subroutine. (unless you wanted a sub that only prints info about where it is defined)
32.   How to install a Perl Module from CPAN


perl -MCPAN -e shell
install DBD::mysql
  
Perl lets you define your own functions to be called like Perl's built-in functions.

Declared as    Called as
sub mylink ($$)    mylink $old, $new

Since prototypes are taken into consideration only at compile time, it naturally falls out that they have no influence on subroutine references like\&foo or on indirect subroutine calls like &{$subref} or $subref->()
 Pass an array to subroutine:
There are two ways you can do this:

    by prototype
    by reference

But before I discuss these--if what you show in your question is about the extent of what you want to do--let me suggest List::MoreUtils::pairwise
So, where you would write this:

my @sum = two_array_sum( @a, @b )

You'd simply write this:

my @sum = pairwise { $a + $b } @a, @b;

By prototype
This works like push. (And just like push it demands to have a @ sigil on something)

sub two_array_sub (\@\@) {
    my ( $aref, $bref ) = @_;
    ...
}

That way when you do this

two_array_sub( @a, @b );

it works. Whereas normally it would just show up in your sub as one long list. They aren't for everybody as you'll see in my discussion below.
By reference
That's the way that everybody is showing you.

some_sub( \@a, \@b );

About prototypes
They're finicky. This won't work if you have refs:

two_array_sub( $arr_ref, $brr_ref );

You have to pass them like this:

two_array_sub( @$arr_ref, @$brr_ref );

However, because making "array expressions" gets really ugly quickly with arrays nested deep, I often avoid Perl's fussiness as you can overload the type of reference Perl will take by putting it in a "character class" construct. \[$@] means that the reference can either be a scalar or array.

sub new_two_array_sub (\[$@]\[$@]) {
    my $ref = shift;
    my $arr = ref( $ref ) eq 'ARRAY' ? $ref : $$ref; # ref -> 'REF';
    $ref    = shift;
    my $brr = ref( $ref ) eq 'ARRAY' ? $ref : $$ref;
    ...
}

So all these work:

new_two_array_sub( @a, $self->{a_level}{an_array} );
new_two_array_sub( $arr, @b );
new_two_array_sub( @a, @b );
new_two_array_sub( $arr, $self->{a_level}{an_array} );

However, Perl is still fussy about this... for some reason:

new_two_array_sub( \@a, $b );
OR
new_two_array_sub( $a, [ 1..3 ] );

Or any other "constructor" that still could be seen as a reference to an array. Fortunately, you can shut Perl up about that with the old Perl 4 &
&new_two_array_sub( \@a, [ 1..3 ] );
Then the mux-ing code in the sub takes care of handling two array references.



.   You have two arrays. Say @arr1 = (1,2,5,6) and @arr2 = (3,4) We need to put the element of @arr2 at @arr1 in such a way that @arr1 would become @arr1= (1,2,3,4,5,6) without using third array.  Hint: use splice function


The Perl splice function is for arrays and is used to remove, replace or add elements.
35.   Inbuilt special variable like $!, $? Etc


Per-filehandle Special Variables
These variables never need to be mentioned in a local()because they always refer to some value pertaining to the currently selected output filehandle - each filehandle keeps its own set of values.
VariableContentsMnemonic
$|If set to nonzero, forces a flush after every write or printWhen you want your pipes to be piping hot
$%Current page number% is page number in nroff
$=Current page length= has horizontal lines
$-Number of lines left on the pagelines_on_page - lines_printed
$~Name of the current report formatClosely related to $^
$^Name of the current top-of-page formatPoints to top of page

Local Special Variables
These variables that are always local to the current block, so you never need to mention them in a local(). All of them are associated with the last successful pattern match.
VariableContentsMnemonic
$1..$9Contains the subpattern from the corresponding set of parentheses in the last pattern matchedlike \1..\9
$&Contains the string matched by the last pattern matchlike & in some editors
$`The string preceding whatever was matched by the last pattern match, not counting patterns matched in nested blocks that have been exited already.` often precedes a quoted string in normal text
$'The string following whatever was matched by the last pattern match, not counting patterns matched in nested blockes that have been exited already. For example:   $_ = 'abcdefghi';
   /def/;
   print "$`:$&:$'\n";    # prints abc:def:ghi
' often follows a quoted string in normal text
$+the last bracket matched by the last search pattern. This is useful if you don't know which of a set of alternative patterns matched. For example:    /Version: (.*)|Revision: (.*)/ && ($rev = $+);be positive and forward looking

Global Special Variables
There are quite a few variables that are global in the fullest sense -- they mean the same thing in every package. If you want a private copy of one of them, you must localize it in the current block.
VariableContentsMnemonic
$_The default input and pattern-searching space. The following pairs are equivalent:    while (<>) {...     # equivalent only in while!
    while ($_ =<>) {...

    /^Subject:/
    $_ =~ /^Subject:/

    y/a-z/A-Z/
    $_ =~ y/a-z/A-Z/

    chop
    chop($_)
underline is understood to be underlying certain undertakings
$.The current input line number of the last filehandle that was read. Rember that only an explicit close on the filehandle resets the line number.many programs use . to mean the current line number
$/The input record separator, newline by default. $/ may be set to a value longer than one character in order to match a multi-character delimiter. If $/ is undefined, no record separator is matched, and<FILEHANDLE> will read everything to the end of the current file./ is used to delimit line boundries when quoting poetry. Or, if you prefer, think of mad slashers cutting things to ribbons.
$\The output record separator for the print operator.You set $\ instead of adding \n at the end of the print.
$,The output field separator for the print operator.What is printed when there is a , in yourprint statement
$"This is similar to $, except that it applies to array values interpolated into a double-quoted string (or similar interpreted string). Default is space.Obvious, I think
$#The output format for numbers display via the printoperator# is the number sign
$$The process number of the Perl running this scriptSame as shells
$?The status returned by the last pipe close, backtick(``) command or system operator. Note that this is the status word returned by the wait() system call, so the exit value of the subprocess is actually ($? >>*)$? & 255 gives which signal, if any, the process died from, and whether there was a core dump. Similar to sh and ksh
$*Set to 1 to do multi-line matching within a string, 0 to tell Perl that it can assume that strings contain a single line, for the purpose of optimizing pattern matches. Default is 0* matches multiple things
$0Contains the name of the file containing the Perl script being executed. Depending on your OS, it may or may not include the full pathname.Same as sh and ksh
$[The index of the first element in an array, and of the first character in a substring.[ begins subscripts
$]The first part of the string printed out when you sayperl -v. It can be used to determine at the beginning of a script whether the Perl interpreter executing the script is in the right range of versions. If used in a numeric context, $] returns version + patchlevel /1000.Is this version of Perl in the "rightbracket"?
$;The subscript separator for multi-dimensional array emulation. If you refer to an associative array element as:   $foo{$a,$b,$c}
it really means:
   $foo{join($;, $a, $b, $c)}
but don't put
   @foo{$a,$b,$c}
which means
   ($foo{$a},$foo{$b},$foo{$c})
Comma (the syntactic subscript separator) is a semi-semicolon. Yeah, it's pretty lame, but $, is already taken for something more important.
$!If used in a numeric context, yields the current value of errno, with all the usual caveats. (This means that you shouldn't depend on the value of $! to be anything in particular unless you've gotten a specific error return indicating a system error.) If used in a string context, yields the corresponding sysem error string.What just went bang?
$@The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.
36.   Piping in and piping out in Perl


pipe is a unidirectional I/O channel that can transfer a stream of bytes from one process to another. Pipes come in both named and nameless varieties. You may be more familiar with nameless pipes, so we'll talk about those first.

Anonymous Pipes

Perl's open function opens a pipe instead of a file when you append or prepend a pipe symbol to the second argument to open. This turns the rest of the arguments into a command, which will be interpreted as a process (or set of processes) that you want to pipe a stream of data either into or out of. Here's how to start up a child process that you intend to write to:
open SPOOLER, "| cat -v | lpr -h 2>/dev/null"
    or die "can't fork: $!";
local $SIG{PIPE} = sub { die "spooler pipe broke" };
print SPOOLER "stuff\n";
close SPOOLER or die "bad spool: $! $?";
This example actually starts up two processes, the first of which (running cat) we print to directly. The second process (running lpr) then receives the output of the first process. In shell programming, this is often called a pipeline. A pipeline can have as many processes in a row as you like, as long as the ones in the middle know how to behave like filters; that is, they read standard input and write standard output.
37.   How to implement stack and queue in Perl?

use push, pop,shift,unshift function
38.   How to find the list of installed modules in Perl?
 command:
pmall
instmodsh
perl -MNet::Ping -e 1
 
39.   Use of BEGIN and END block.


There are two special code blocks for perl modules - BEGIN and END. These blocks are executed when a module is first loaded, and when the perl interpreter is about to unload it, respectively.
Here's an example for a logging module that makes use of this facility:
# File : MyLog.pm
#

package MyLog;

use strict;
use warnings;

BEGIN
{
    open MYLOG, ">", "mylog.txt";
}

sub log
{
    my $what = shift;

    # Strip the string of newline characters
    $what =~ s/\n//g;

    # The MYLOG filehandle is already open by virtue of the BEGIN
    # block.
    print MYLOG $what, "\n";
}

END
{
    close(MYLOG);
}

1;
40.   Simulate the behaviour of ‘use lib’ pragma using BEGIN block.


use lib "$ENV{HOME}/libperl";   # add ~/libperl
no lib ".";                     # remove cwd
This pragma simplifies the manipulation of @INC at compile time. It is typically used to add extra directories to Perl's search path so that later dorequire, and use statements will find library files that aren't located in Perl's default search path.


File Handling in Perl
1.     File Testing. Binary or text, size, accessed like –e, -f, -a, -c –m etc

$neededfile="myfile.cgi";
if (-e $neededfile)

 #proceed with your code
}
File exists, has a size of zero: -z
File exists, has non-zero size: -s
Readable: -r
Writable: -w
Executable: -x
You can test the file to see if it is text or if it is binary using these:
Text File: -T
Binary File: -B
  
2.     Use of the special file handle _. (Note : its just _ not $_). Using this can significantly improve performance in many cases.
sub _() as a means to localise text
 
3.     Syntax for opening, appending, reading, writing files


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;
}
close(CHECKBOOK);

4.     How to assign File handle into an array instead of using while loop?

foreach $file (@filehandles) { print $file "File $count"; close $file; $count++; }
5.     How to delete a file?
print "content-type: text/html \n\n"; #The header
@files = ("newtext.txt","moretext.txt","yetmoretext.txt");
foreach $file (@files) {
    unlink($file);
}
6.     How to copy or move a file?
     use File::Copy qw(copy);    
    copy $old_file, $new_file;

    use File::Copy qw(move);
     move $old_name, $new_name;
7.     What the various file permissions (flags) in Perl?


< or rRead Only Access
> or wCreates, Writes, and Truncates
>> or aWrites, Appends, and Creates
+< or r+Reads and Writes
+> or w+Reads, Writes, Creates, and Truncates
+>> or a+Reads, Writes, Appends, and Creates

8.     Given a file, count the word occurrence (case insensitive)
open(FILE,"filename");
@array=<FILE>;
$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";

 9.     Displaying file contents using hash in Perl

my %hash;
while (<FILE>)
{
   chomp;
   my ($key, $val) = split /=/;
   $hash{$key} .= exists $hash{$key} ? ",$val" : $val;
}

This walks through every line splitting on the '=' sign and either adds an entry or appends to an existing entry in the hash table.

Thursday, January 24, 2013

Perl Interview questions and Answers



Web based & Perl CGI
1.     What do you know about CGI.pm?
 CGI.pm is a large and widely used Perl module for programming Common Gateway Interface (CGI) web applications, providing a consistent API for receiving user input and producing HTML or XHTML output.
2.     How to set sessions and cookies and how to implement in Perl?


you'll define the cookie properties by calling the cookie method. In this example, the name of the cookie is MY_COOKIE, while the value of the cookie is "BEST_COOKIE=chocolatechip". You create a cookie just like this, by specifying the name and value of the cookie when using the cookie method:
$cookie = $query->cookie(-name=>'MY_COOKIE',
    -value=>'BEST_COOKIE=chocolatechip',
    -expires=>'+4h',
    -path=>'/');
get cookies:

$theCookie = $query->cookie('MY_COOKIE');
set session:
$session = new CGI::Session(DSN, SID, DSN_OPTIONS);
get session:
my $first_name  = $session->param("first_name"); 

3.     How to display JSON based output
4.     Why two \n in print “Content-type: text/html \n\n”;
Database oriented
1.     How to connect database using DBI?
2.     What are the ways you know to get records from the table (fetchrow_hashref/arrayref)

1. @row = $conn->fetchrow_array;

2. $row = $conn->fetchrow_arrayref;

3. $row = $conn->fetchrow_hashref;
fetchrow_array:
dbopen.pl

#!/usr/bin/perl
require "dbconfig.pl";
$dbconnect = DBI->connect($dbase,$user,$pass) or die "connection Error:$DBI::errstr\n";
dbconfig.pl
#!/usr/bin/perl
$dbase = 'dbi:mysql:siva';
$user = 'root';
$pass = 'siva123';
dbclose.pl
#!/usr/bin/perl
$dbconnect->disconnect();
Test.pl
#!/usr/bin/perl
use DBI;
require "dbopen.pl";
$sql = "select id,emp_fname,emp_lname,emp_id from stech_emp limit 30,10";
$conn =$dbconnect->prepare($sql);
$conn->execute or die "SQL Error:$DBI::errstr\n";
while (@row = $conn->fetchrow_array) {

print "$row[0]\t$row[1]\t$row[3]\n";


}

$conn->finish();
require "dbclose.pl";

OUTPUT:

root@itadmin-desktop:/var/www/cgi# perl Test.pl
44 Loganayagi 1010
45 Amala 1014
46 Vidhya 1009
47 Nithya 4006
48 Vanitha 1020
49 Saraswathi 1021
50 Maheswari 4009
51 Kalpana 4010
52 Renuga 4017
53 Nisha 4015
fetchrow_arrayref :
dbopen.pl

#!/usr/bin/perl
require "dbconfig.pl";
$dbconnect = DBI->connect($dbase,$user,$pass) or die "connection Error:$DBI::errstr\n";
dbconfig.pl
#!/usr/bin/perl
$dbase = 'dbi:mysql:siva';
$user = 'root';
$pass = 'siva123';
dbclose.pl
#!/usr/bin/perl
$dbconnect->disconnect();
Test1.pl
#!/usr/bin/perl
use DBI;
require "dbopen.pl";
$sql = "select id,emp_fname,emp_lname,emp_id from stech_emp limit 30,10";
$conn =$dbconnect->prepare($sql);
$conn->execute or die "SQL Error:$DBI::errstr\n";
while (@row = $conn->fetchrow_arrayref) {

print "$row->[0]\t$row->[1]\t$row->[3]\n";


}

$conn->finish();
require "dbclose.pl";

OUTPUT:

root@itadmin-desktop:/var/www/cgi# perl Test1.pl
44 Loganayagi 1010
45 Amala 1014
46 Vidhya 1009
47 Nithya 4006
48 Vanitha 1020
49 Saraswathi 1021
50 Maheswari 4009
51 Kalpana 4010
52 Renuga 4017
53 Nisha 4015
fetchrow_hashref :

dbopen.pl

#!/usr/bin/perl
require "dbconfig.pl";
$dbconnect = DBI->connect($dbase,$user,$pass) or die "connection Error:$DBI::errstr\n";
dbconfig.pl
#!/usr/bin/perl
$dbase = 'dbi:mysql:siva';
$user = 'root';
$pass = 'siva123';
dbclose.pl
#!/usr/bin/perl
$dbconnect->disconnect();
Test2.pl
#!/usr/bin/perl
use DBI;
require "dbopen.pl";
$sql = "select id,emp_fname,emp_id from stech_emp limit 30,10";
$conn =$dbconnect->prepare($sql);
$conn->execute or die "SQL Error:$DBI::errstr\n";
while ($row = $conn->fetchrow_hashref) {

print "$row->{id}\t$row->{emp_fname}\t$row->{emp_id}\n";


}

$conn->finish();
require "dbclose.pl";
OUTPUT:

root@itadmin-desktop:/var/www/cgi# perl Test2.pl
44 Loganayagi 1010
45 Amala 1014
46 Vidhya 1009
47 Nithya 4006
48 Vanitha 1020
49 Saraswathi 1021
50 Maheswari 4009
51 Kalpana 4010
52 Renuga 4017
53 Nisha 4015
Object Oriented Perl
1.     Diff b/w module and package
    * Packages are perl files with .pm extn and is considered a separate namespace. So a package is nothing but group of related scalars,arrays,hashes and subroutines for a specific purpose.
    Once a package is included in a .pl file (using "use") and you want to call one of the subroutines of the package, you may have to use the scope resolution operator &package::subroutine1
    * Modules are packages but which has the capabilities of exporting selective subroutines/scalars/arrays/hashes of the package to the namespace of the main package itself. So for the interpreter these look as though the subroutines are part of the main package itself and so there is no need to use the scope resolution operator while calling them.
2.     Diff b/w class and package (rarely asked though )
3.     How do you call any subroutine in object oriented fashion? Hint: bless operator
4.     Use base, EXPORT, EXPORT_OK
5.     Difference between ISA and EXPORT
6.     Use Base related questions
7.     Use of AUTOLOAD function.
Regular Expression in Perl
1.     IP Address validation
2.     Email id Validation
3.     More than one @ is there. Give regex to store username and domain name after encountering last @ (Last @ will be the splitting point and more than one special characters can be there )
4.     What are the uses of different modifiers

5.     Group, range, meta-character etc
6.     m, s, tr
7.     Replace the last ‘x’ in a string with ‘ax’ in one regex. Example : abcxdefgxgaxa should become abcxdefgxgaaxa
8.     Perl regular expression is greedy. Can you explain it with one example?
9.     Can you check palindrome condition using regular expression in perl? (Hint: regex doesn’t support recursion or counting facility )
Perl One Liner
1.     What is Perl one liner and where you will use it?
2.     What are the different options in Perl one Liner. Explain in details
3.     Add a blank line before every line.
4.     Remove blank lines form a file.
5.     Print the total number of lines in a file (emulate wc -l).
6.     Print the number of non-empty lines in a file.
7.     What option you will use to check syntax only without executing it?
8.     Which option is meant to enable all warnings or disable all warning inpite of using use warning or no warnings respectively?