Note : Questions Marked in Red, answer needs to rephrase to be more clear.
Q1. What is a subroutine?
A1. Subroutine in perl is a block of code specially combined/grouped to perform a particular task.Which can called at any point of time in a perl program. Advantage using Subroutine
a) helps in modular programming making it easier to understand and maintain
b) eliminates duplication by reusing the same code/calling the subroutine.
Q2.What is difference between a subroutine and function?
A2. function and subroutine are subprograms used in fortran. function subprograms are used to compute a single value,while subroutine subprogram are used to compute several values or to perform task. main difference between a subroutine and a function as follows:
1. No value is associated with the name of a subroutine,while the name of a function subprogram must have a value, numerical or logical.
2. A subroutine may be invoked only by a special calling statement-the call statement. The name of a function subprogram may be used in the same way as library functions,,i.e.,in arithmetic statements,etc.
3. A FUNCTION subprogram must have at least one argument, while a subroutine need not have any.
4. Since a function subprogram computes atleast one value, it must contain a return statement. A SUBROUTINE subprogram need not contain return statement.
Q3. Given a file, count the word occurrence (case insensitive)
A3.
$infile='txt';
open INFILE,"$infile" or die ;
while(<INFILE>) {
chomp;
$r++ for $_ =~/the_word/g;
}
print "r $r ";
close INFILE;
Q4. Explain the difference between "my" and "local" variable scope declarations. ?
A4. The variables declared with my() are visible only within the scope of the block which names them. They are not visible outside of this block, not even in routines or blocks that it calls. local() variables, on the other hand, are visible to routines that are called from the block where they are declared. Neither is visible after the end (the final closing curly brace) of the block at all.
Q5. Name all the prefix dereferencer in perl?
A5. The symbol that starts all scalar variables is called a prefix dereferencer. The different types of dereferencer are.
a) $-Scalar variables
b) %-Hash variables
c) @-arrays
d) &-subroutines
e) Type globs-*myvar stands for @myvar, %myvar.
Q6. Which of these is a difference between C++ and Perl?
A6. Perl can have objects whose data cannot be accessed outside its class, but C++ cannot.
Perl can use closures with unreachable private data as objects, and C++ doesn't support closures. Furthermore, C++ does support pointer arithmetic via `int *ip = (int*)&object', allowing you do look all over the object. Perl doesn't have pointer arithmetic. It also doesn't allow `#define private public' to change access rights to foreign objects. On the other hand, once you start poking around in /dev/mem, no one is safe.
Q7. What is a short circuit operator?
A7. The C-Style operator, ||, performs a logical (or) operation and you can use it to tie logical clauses together, returning an overall value of true if either clause is true. This operator is called a short-circuit operator because if the left operand is true the right operand is not checked or evaluated.
Q8. What's the significance of @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS list & hashes in a perl package? With example?
A8. @ISA -> each package has its own @ISA array. this array keep track of classes it is inheriting.
Ex: package child;
@ISA=( parentclass);
@EXPORT this array stores the subroutins to be exported from a module.
@EXPORT_OK this array stores the subroutins to be exported only on request.
Q9. Why does Perl not have overloaded functions?l
A9.Because you can inspect the argument count, return context, and object types all by yourself. In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they're references and simple pattern matching like /^d+$/ otherwise. In languages like C++ where you can't do this, you simply must resort to overloading of functions.
OR
In C++ function overloading is being used to call different function with different number of arguments OR type while in Perl, function/subroutine is not dependent on number of arguments passing to it.
Ex.
my $x=add(2,3,4,5,6,7);
print "x=$x";
sub add
{
$y= $y+$_ for @_; # So here subroutine does not care how many arguments being passed.
return $y;
}
Q10. Which has the highest precedence, List or Terms? Explain?
A10. Terms have the highest precedence in perl. Terms include variables, quotes, expressions in parenthesis etc. List operators have the same level of precedence as terms. Specifically, these operators have very strong left word precedence.
Q11. How many ways can we express string in Perl?
A11. For example 'this is a string' can be expressed in:
"this is a string"
qq/this is a string like double-quoted string/
qq^this is a string like double-quoted string^
q/this is a string/
q&this is a string&
q(this is a string)
Note : qw(this is an array) is for array not for string and it returns a list of strings, separating the delimited string by white space.
Q12. How do I set environment variables in Perl programs?
A12. As you may remember, "%ENV" is a special hash in Perl that contains the value of all your environment variables. Because %ENV is a hash, you can set environment variables just as you'd set the value of any Perl hash variable. Here's how you can set your PATH variable to make sure the following four directories are in your path::
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/home/yourname/bin';
Q13. How do you connect to database in perl
A13. There is DBI module.
use DBI;
my $dbh = DBI->connect('dbi:Oracle:orcl', 'username', 'password',)
where username and password is yours. (This is example for oracle database)
For Sybase:
use DBI;
my $dbh = DBI->connect('dbi:Sybase:server=$SERVER', 'username', 'password')
Q14. What is meant by splicing arrays explain in context of list and scalar.
A14. Splicing an array means adding elements from a list to that array, possibly replacing elements now in the array. In list context, the splice function returns the elements removed from the array. In scalar context, the splice function returns the last element removed.
Q15. Explain about Typeglobs?
A15. Type globs are another integral type in perl. A typeglob`s prefix derefrencer is *, which is also the wild card character because you can use typeglobs to create an alias for all types associated with a particular name. All kinds of manipulations are possible with typeglobs.
Q16. What are the three ways to empty an array?
A16. The three different ways to empty an array are as follows
1) You can empty an array by setting its length to a negative number.
2) Another way of empting an array is to assign the null list ().
3) Try to clear an array by setting it to undef, but be aware when you set to undef.
In 3 ways..
1. $#arr= -1
2. @arr= ()
3. @arr = undef (not recommended you might get an array having 1 element "undef"
Q17. How do you give functions private variables that retain their values between calls?
A17. Create a scope surrounding that sub that contains lexicals. Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus: { my $i = 0; sub next_i { $i++ } sub last_i { --$i } } creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.
Q18. Write perl code to find prime numbers
A18.
#!/usr/bin/perl
print "Find primes from: ";
$o = <>;
print "to: ";
$e = <>;
for($i=$o; $i<=$e; $i++)
{
$p=0;
for($j=1; $j<=$i; $j++)
{
if($i % $j==0)
{
$prime_[$p] = "$j";
$p++;
}
if ($prime_[1] == $i)
{
print "$i is prime";
print "\n";
}
}
}
You may as well write
for($i=$o; $i<=$e; $i++){
as
print "2 is prime\n" if $o == 2;
$o++ if !($o%2); # increase by 1 if number is not odd OR even
for ( $i=$o; $i<=$e; $i=$i+2) {
That way you start on an odd number and account for the only even number which is prime. There is no need to check
even numbers after 2.
Note : 1 is not a prime number, why?
Very simple answer actually. The definition of a prime number is a natural number that has exactly two distinct natural number divisors. And the definition of a composite number is a natural number that has more than two finite, distinct natural number divisors.
One has just one natural number divisor (1), thus it doesn't fit in either category. Zero has an infinite number of natural number divisors, thus it doesn't either.
Q19. Write a regular expression for validating an email address.
A19.
/^\w[\w\.\-]*\w\@\w[\w\.\-]*\w(\.\w{2,4})$/
Example:
my $email='da.bc@ab.c-c-c-c.com';
if($email=~ /^\w[\w\.\-]*\w\@\w[\w\.\-]*\w(\.\w{2,4})$/i)
{
print"\n valid email\n";
}
else
{
print"\nnot a valid\n";
}
Note : It should start with \w( 0-9 or a-z or A-Z), contains @ and end with .\w{2,4} , in between it may have any number of \w, \. , \-
following module is available in Perl to validate email address Email::Valid
Link :
http://www.perlmonks.org/?node_id=327912
http://www.codetoad.com/asp_email_reg_exp.asp
http://search.cpan.org/~rjbs/Email-Valid-0.184/lib/Email/Valid.pm
Q20. Write a program in Perl to reverse a string [Ex. Welcome to hell ==> lleh ot emoclew]
A20. There are multiple ways to do it :
1) Using an array:
my $str ="welcome to hell";
my @arr = split(//,$str); # it will return an array of characters
my @rev;
my $i;
foreach (@arr) {
$rev[scalar @arr - $i] = $_; #take a new array and assign its content in reverse order
$i++;
}
print @rev;
--------------------------------OR------------------------------
my $str ="welcome to hell";
my @rev;
foreach (split(//,$str))
{
unshift @rev, $_; # Will add element in reverse order Or from bottom
}
print @rev;
2) with out using array
my $str ="welcome to hell";
my $rev;
foreach (split(//,$str))
{
$rev= "$_" . "$rev"; # Use concatenation technique in reverse order
}
print $rev;
Note : If you want to reverse words then use space to split the string split(/\s/,$str) or split(/ /,$str) [Ex. Welcome to hell ==> hell to welcome]
Q21. Explain Push/Pop/Shift/Unshift with exampls
A21.
my @arr = ("b","c","d");
push @arr, "e";
print "@arr \n"; # Add on top b c d e
pop @arr ;
print "@arr \n"; # Remove from top b c d
unshift @arr, "a"; # Add from bottom a b c d
print "@arr \n";
shift @arr; # Remove from bottom b c d
print "@arr \n";
Q22. How to read a particular line from a file
A22.
open FILE, "./fileName.txt" or die "can not open file fileName.txt";
while (<FILE>)
{
print if($.==3) #Perl special variable $. contains current line number
}
Q23. Write a regular expression to validate a mobile number
A23.
my $phone="9821129324";
if($phone=~/^9[\d]{9}$/) # Mobile number should start from 9 and have 10 digit
{
print "valid phone number";
}
else
{
print "not a valid mobile number";
}
Q24. How to install a module
A24.
A. DECOMPRESS
Decompress the file with gzip -d yourmodule.tar.gz
B. UNPACK
Unpack the result with tar -xof yourmodule.tar
C. BUILD
Go into the newly-created directory and type:
perl Makefile.PL
make
make test
D. INSTALL While still in that directory, type:
make install
Q25. What is the difference between for & foreach.
A25. Back in the early days of Perl, Larry Wall decided to borrow from both C (the "for" loop) and Csh (the "foreach" loop) to provide a means of a computed iterator or a simple list enumeration. Apparently, he noticed that Perl could always distinguish (by the contents of the parentheses part of the statement) whether a for-loop or a foreach-loop was needed, Larry decided to make the keywords interchangable, simply because they were both "iterators" and the more common of the two loops (the foreach loop) could be spelled with 4 fewer characters.
To summarize: the "for" loop is from C, and looks like:
for (initializer; test; incrementor) { body }
The "foreach" loop is from csh, and looks like:
foreach $optional_iterator (list) { body }
However, you can spell "for" as "foreach" and vice versa, and Perl won't care... it'll correct for your misspelling. :)
------------------x--------------x--------------------
There are two types of for loop in Perl, the C-style one
for ($x = 1; $x <= 10; $x ++)
{
...
}
and the other sort
for $x ( 1 .. 10 )
{
...
}
Both can be written with foreach instead of for as the former is just a synonym for the latter.
External Links:
http://www.coolinterview.com/type.asp?iType=108
http://docs.limesurvey.org/Using+regular+expressions#Email_Validation: