Saturday, December 25, 2010

Perl Basic Interview Question and answer

  1. How many type of variable in perl
    Perl has three built in variable types
    1. Scalar
    2. Array
    3. 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 un-ordered list of values position by keys.
  1. 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.


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


  1. 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"


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


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

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


  1. How to merge two array?
@a=(1, 2, 3, 4);
@b=(5, 6, 7, 8);
@c=(@a, @b);
print "@c";


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


  1. How to get the hash size
%ages = ('Martin' => 28, 'Sharon' => 35, 'Rikke' => 29);
print "Hash size: ",scalar keys %ages,"\n";


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


  1. PERL Conditional Statements
The conditional statements are if and unless


  1. Perl supports four main loop types:
While, for, until, foreach


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


  1. Renaming a file
rename ("/usr/test/file1.txt", "/usr/test/file2.txt" );


  1. Deleting an existing file
unlink ("/usr/test/file1.txt");


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


  1. 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///

  1. What is the difference between chop & chomp functions in perl?
chop is used remove last character, chomp function removes only line endings.

  1. Email address validation – perl
if ($email_address =~ /^(\w¦\-¦\_¦\.)+\@((\w¦\-¦\_)+\.)+[a-zA-Z]{2,}$/)
{
print "$email_address is valid";
}
else {
print "$email_address is invalid";
}

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

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

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


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

No comments: