Friday, December 24, 2010

Perl Interview Questions

Perl Interview Questions and Answers:

1. What are the arguments we normally use for Perl Interpreter
Ans:

 -e for Execute
 -c to compile
 -d to call the debugger on the file specified
 -T for traint mode for security/input checking
 -W for show all warning mode (or -w to show less warning)

2. What is the difference between ‘use’ and ‘require’ function?
Ans: 
Use:
1. the method is used only for modules (only to include .pm type file)
2. the included object are verified at the time of compilation.
3. No Need to give file extension.

Require:
1. The method is used for both libraries (package) and modules
2. The include objects are verified at the run time. 3. Need to give file Extension.


3. What is the use of ‘chomp’ ? what is the difference between ‘chomp’ and ‘chop’?
Ans: ‘chop’ function only removes the last character completely ‘from the scalar, where as
‘chomp’ function only removes the last character if it is a newline. by default, chomp only
removes what is currently defined as the $INPUT_RECORD_SEPARATOR. whenever
you call ‘chomp ‘, it checks the value of a special variable ‘$/’. whatever the value of ‘$/’ is
eliminated from the scaler. by default the value of ‘$/’ is ‘n’


4. Print this array @arr in reversed case-insensitive order Ans: @solution = sort {lc $a comp lc$b } @arr.


5. What is ‘->’ in Perl?
Ans: It is a symbolic link to link one file name to a new name. So let’s say we do it like
file1-> file2, if we read file1, we end up reading file2.


6. How do you check the return code of system call?
Ans: System calls “traditionally” returns 9 when successful and 1 when it fails. System
(cmd) or die “Error in command”.


7. What is the use of -M and -s in the above script?
Ans:
 -s means is filename a non-empty file
-M how long since filename modified


8. How to substitute a particular string in a file containing million of record?
Ans: perl -p -i.bak -e ‘s/search_str/replace_str/g’ filename


9.  How do you know the reference of a variable whether it is a reference, scaler, hash or
array?

Ans: ref


10. What is meant by a ‘pack’ in perl?
Ans: Pack converts a list into a binary representation. Takes an array or list of values and
packs it into a binary structure, returning the string containing the structure it takes a
LIST of values and converts it into a string. The string contains a con-catenation of the
converted values. Typically, each converted values looks like its machine-level
representation. For example, on 32-bit machines a converted integer may be represented
by a sequence of 4 bytes.


11. How to implement stack in Perl?
Ans: Through push() and shift() function. push adds the element at the last of array and
shift() removes from the beginning of an array.


12. What is Grep used for in Perl?
Ans: Grep is used with regular expression to check if a particular value exists in an array.
It returns 0 it the value does not exists, 1 otherwise.


13. How to code in Perl to implement the tail function in UNIX?
Ans: You have to maintain a structure to store the line number and the size of the file at
that time e.g. 1-10 bytes, 2-18 bytes.. You have a counter to increase the number of lines to
find out the number of lines in the file. once you are through the file, you will know the
size of the file at any nth line, use ‘sysseek’ to move the file pointer back to that position
(last 10) and then tart reading till the end.


14. Explain the difference between ‘my’ and ‘local’ variable scope declarations?
Ans: Both of them are used to declare local variables. The variables declared with ‘my’
can live only within the block and cannot gets its visibility inherited functions called
within that block, but one defined as ‘local’ can live within the block and have its visibility
in the functions called within that block.


15. How do you navigate through an XML documents?
Ans: You can use the XML::DOM navigation methods to navigate through an
XML::DOM node tree and use the get node value to recover the data. DOM Parser is used
when it is need to do node operation. Instead we may use SAX parser if you require
simple processing of the xml structure.


16. How to delete an entire directory containing few files in the directory?
Ans: rmtree($dir); OR, you can use CPAN module File::Remove Though it sounds like
deleting file but it can be used also for deleting directories. &File::Removes::remove
(1,$feed-dir,$item_dir);





19. What is it meant by ‘$_’?
Ans: It is a default variable which holds automatically, a list of arguments passed to the
subroutine within parentheses.


20. How to connect to sql server through Perl?
Ans: We use the DBI(Database Independent Interface) module to connect to any
database.
use DBI;
$dh = DBI->connect(“dbi:mysql:database=DBname”,”username”,”password”);
$sth = $dh->prepare(“select name, symbol from table”);
$sth->execute();
while(@row = $sth->fetchrow_array()){
 print “name =$row[0].symbol= $row[1];
 }

$dh->disconnect


21. What is the purpose of -w, strict and -T?
Ans:

-w option enables warning
– strict pragma is used when you should declare variables before their use -T is taint mode. TAint mode makes a program more secure by keeping track of arguments which are passed from external source.


22. What is the difference between die and exit?
Ans: Die prints out STDERR message in the terminal before exiting the program while exit
just terminate the program without giving any message.

Die also can evaluate expressions before exiting.

23. Where do you go for perl help?
Ans: perldoc command with -f option is the best. I also go to search.cpan.org for help.

24. What is the Tk module?
Ans: It provides a GUI interface

25. What is your favourite module in Perl?
Ans:  CGI and DBI.

CGI (Common Gateway Interface) because we do not need to worry about the subtle features of form processing.


26. What is hash in perl?
Ans: A hash is like an associative array, in that it is a collection of scalar data, with individual elements selected by some index value which essentially are scalars and called as keys. Each key corresponds to some value. Hashes are represented by % followed by some name.


27. What does ‘qw()’ mean? what’s the use of it?
Ans: qw is a construct which quotes words delimited by spaces. use it when you have long list of words that are into quoted or you just do not want to type those quotes as you type out a list of space delimited words. Like @a = qw(1234) which is like
@a=(“1″,”2″,”3″,”4″);


28. What is the difference between Perl and shell script?
Ans: Whatever you can do in shell script can be done in Perl.

However
1. Perl gives you an extended advantage of having enormous library.
2. You do not need to write everything from scartch.

29. What is stderr() in perl?
Ans: Special file handler to standard error in any package.


30. What is a regular expression?
Ans: It defines a pattern for a search to match.


31. What is the difference between for and foreach?
Ans: Functionally, there is no difference between them.


32. What is the difference between exec and system?
Ans: exec runs the given process, switches to its name and never returns while system forks off the given process, waits for its to complete and then return.


33. What is CPAN?
Ans: CPAN is comprehensive Perl Archive Network. It’s a repository contains thousands of Perl Modules, source and documentation, and all under GNU/GPL or similar license.
You can go to www.cpan.org for more details. Some Linux distribution provides a till names ‘cpan; which you can install packages directly from cpan.


34. What does this symbol mean ‘->’?
Ans: In Perl it is an infix dereference operator. For array subscript, or a hash key, or a subroutine, then its must be a reference. Can be used as method invocation.


35. What is a DataHash()
Ans: In Win32::ODBC,  DataHash() function is used to get the data fetched through the sql statement in a hash format.


36. What is the difference between C and Perl?
Ans: make up


37. Perl regular exp are greedy. what is it mean by that?
Ans: It tries to match the longest string possible.


38. What does the world ‘&my variable’ mean?
Ans: &myvariable is calling a sub-routine. & is used to indentify a subroutine.


39. What is it meant by @ISA, @EXPORT, @EXPORT_OK?
Ans:

@ISA -> each package has its own @ISA array. This array keeps track of classes it is inheriting.
      Ex:
            package child;
           @ISA=(parent class);
@EXPORT this array stores the subroutines to be exported from a module.
@EXPORT_OK this array stores the subroutines to be exported only on request.


40. What package you use to create windows services?
Ans: use Win32::OLE.


41. How to start Perl in interactive mode?
Ans: perl -e -d 1 PerlConsole.


42. How do I set environment variables in Perl programs?
Ans: You can just do something like this: $ENV{‘PATH’} = ‘…’; 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/your name/bin’.


43. What is the difference between C++ and Perl?
Ans: 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.


43. How to open and read data files with Perl?
Ans: 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 = ; 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 = ) { 
      print $record; 

close(CHECKBOOK);


45. How do i do fill_in_the_blank for each file in a directory?
Ans: #!/usr/bin/perl –w
opendir(DIR, “.”);
@files = readdir(DIR);
closedir(DIR);
foreach $file (@files)
{
   print “$file\n”;
}


46. How do I generate a list of all .html files in a directory
Ans: Here is a snippet of code that just prints a listing of every file in teh current directory.
That ends with the entension
#!/usr/bin/perl –w
opendir(DIR, “.”);
@files  = grep(/\.html$/, readdir(DIR));
closedir(DIR);
foreach $file (@files) { print “$file\n”; }


47. What is Perl one-liner?
Ans: There are two ways a Perl script can be run: –from a command line, called oneliner, that means you type and execute immediately on the command line. You’ll need the -e option to start like “C:\ %gt perl -e “print \”Hello\”;”. One-liner doesn’t mean one Perl statement. One-liner may contain many statements in one line. –from a script file, called Perl program.

48. Assume both a local($var) and a my($var) exist, what’s the difference between ${var}
and ${“var”}?
Ans: ${var} is the lexical variable $var, and ${“var”} is the dynamic variable $var. Note that because the second is a symbol table lookup, it is disallowed under `use strict “refs”‘. The words global, local, package, symbol table, and dynamic all refer to the kind of variables that local() affects, whereas the other sort, those governed by my(), are variously knows as private, lexical, or scoped variable.

49. What happens when you return a reference to a private variable?
Ans: Perl keeps track of your variables, whether dynamic or otherwise, and doesn’t free things before you’re done using them


50. What are scalar data and scalar variables?
Ans: Perl has a flexible concept of data types. Scalar means a single thing, like a number or string. So the Java concept of int, float, double and string equals to Perl\’s scalar in concept and the numbers and strings are exchangeable. Scalar variable is a Perl variable that is used to store scalar data. It uses a dollar sign $ and followed by one or more alphanumeric characters or underscores. It is case sensitive.


51. Assuming $_ contains HTML, which of the following substitutions will remove all tags in it?
Ans: You can’t do that. If it weren’t for HTML comments, improperly formatted HTML, and tags with interesting data like , you could do this. Alas, you cannot. It takes a lot more smarts, and quite frankly, a real parser.


52. What is the output of the following Perl program?
$p1 = “prog1.java”;
$p1 =~ s/(.*)\.java/$1.cpp/;
print “$p1\n”;
Ans: prog1.cpp

53. Why aren’t Perl’s patterns regular expressions? Ans: Because Perl patterns has backreferences. A regular expression by definition must be able to determine the next state in the finite automaton without requiring any extra memory to keep around previous state. A pattern /([ab]+)c\1/ requires the state machine to remember old states, and thus disqualifies such patterns as being regular expressions in the classic sense of the term.

54. What does Perl do if you try to exploit the execve(2) race involving setuid scripts?
Ans: Sends mail to root and exits. It has been said that all programs advance to the point of being able to automatically read mail. While not quite at that point (well, without having a module loaded), Perl does at least automatically send it.


55. How do I do for each element in a hash? Ans: Here’s a simple technique to process each element in a hash:
#!/usr/bin/perl -w
%days = ( ‘Sun’ =>’Sunday’, ‘Mon’ => ‘Monday’, ‘Tue’ => ‘Tuesday’, ‘Wed’ => ‘Wednesday’, ‘Thu’ => ‘Thursday’, ‘Fri’ => ‘Friday’, ‘Sat’ => ‘Saturday’ );
foreach $key (sort keys %days)  {
print  “The long name for $key is $days{$key}.\n”;
 }

56. How do I sort a hash by the hash key?
Ans:. Suppose we have a class of five students. Their names are kim, al, rocky, chrisy, and jane. Here’s a test program that prints the contents of the grades hash, sorted by student name:
 #!/usr/bin/perl –w
%grades = ( kim => 96, al => 63, rocky => 87, chrisy => 96, jane => 79, );
print “\n\tGRADES SORTED BY STUDENT NAME:\n”;
foreach $key (sort (keys(%grades))) {
    print “\t\t$key \t\t$grades{$key}\n”;
}

The output of this
program looks like this: GRADES SORTED BY STUDENT NAME: al 63 chrisy 96 jane
79 kim 96 rocky 87

57. How do you print out the next line from a filehandle with all its bytes reversed?
Ans: print scalar reverse scalar surprisingly enough, you have to put both the reverse and the in to scalar context separately for this to work.

58. How do I send e-mail from a Perl/CGI program on a Unix system?
Ans: Sending e-mail from a Perl/CGI program on a Unix computer system is usually pretty simple. Most Perl programs directly invoke the Unix sendmail program. We’ll go through a quick example here. Assuming that you’ve already have e-mail information you need, such as the send-to address and subject, you can use these next steps to generate and send the e-mail message: # the rest of your program is up here …
open(MAIL, “|/usr/lib/sendmail -t”);
print MAIL “To: $sendToAddress\n”;
print MAIL “From: $myEmailAddress\n”;
print MAIL “Subject: $subject\n”;
print MAIL “This is the message body.\n”;
 print MAIL “Put your message here in the body.\n”;
close (MAIL);


59. How to read from a pipeline with Perl?
Ans: To run the date command from a Perl program, and read the output of the command,
all you need are a few lines of code like this:
open(DATE, “date|”);
$theDate = ;
close(DATE);
The open() function runs the external date command, then opens a file handle DATE to the output of the date command. Next, the output of the date command is read into the variable $theDate through the file handle DATE. Example 2: The following code runs the “ps -f” command, and reads the output:
open(PS_F, “ps -f|”);
while (){
     ($uid,$pid,$ppid,$restOfLine) = split; # do whatever I want with the variables here …
}
close(PS_F);

60. Why is it hard to call this function: sub y { “because” }
Ans. Because y is a kind of quoting operator. The y/// operator is the sed-savvy synonym
for tr///. That means y(3) would be like tr(), which would be looking for a second string,
as in tr/a-z/A-Z/, tr(a-z)(A-Z), or tr[a-z][A-Z].

61. Why does Perl not have overloaded functions?
Ans: 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.


62. What does read() return at end of file?
Ans: 0. A defined (but false) 0 value is the proper indication of the end of file for read() and sysread().

63. How do I sort a hash by the hash value?
Ans: Here’s a program that prints the contents of the grades hash, sorted numerically by the hash value:
#!/usr/bin/perl –w
# Help sort a hash by the hash ‘value’, not the ‘key’. To highest).
# sub hashValueAscendingNum { $grades{$a} $grades{$b}; }
# Help sort a hash by the hash ‘value’, not the ‘key’.
# Values are returned in descending numeric order
# (highest to lowest).
sub hashValueDescendingNum {
    $grades{$b} $grades{$a};
 }
%grades = ( student1 => 90, student2 => 75, student3 => 96, student4 => 55, student5 => 76 );
print “\n\tGRADES IN ASCENDING NUMERIC ORDER:\n”;
foreach $key (sort hashValueAscendingNum (keys(%grades))) {
print “\t\t$grades{$key} \t\t $key\n”;
 }
print “\n\tGRADES IN DESCENDING NUMERIC ORDER:\n”;
foreach $key (sort hashValueDescendingNum (keys(%grades))) {
print “\t\t$grades{$key} \t\t $key\n”;
 }


64. How do find the length of an array? Ans: scalar @array

65. What value is returned by a lone `return;’ statement? Ans: The undefined value in scalar context, and the empty list value () in list context. This way functions that wish to return failure can just use a simple return without worrying about the context in which they were called.

66. What’s the difference between /^Foo/s and /^Foo/?
Ans: The second would match Foo other than at the start of the record if $* were set. The deprecated $* flag does double duty, filling the roles of both /s and /m. By using /s, you suppress any settings of that spooky variable, and force your carets and dollars to match only at the ends of the string and not at ends of line as well — just as they would if $* weren’t set at all.

67. Does Perl have reference type?
Ans: Yes. Perl can make a scalar or hash type reference by using backslash operator. For example

$str = “here we go”;                  # a scalar variable
$strref = \$str;                           # a reference to a scalar
@array = (1..10);                     # an array
$arrayref = \@array;                 # a reference to an array Note that the reference itself is a scalar.

68. How to dereference a reference?
Ans: There are a number of ways to dereference a reference. Using two dollar signs to dereference a scalar. $original = $$strref; 

Using @ sign to dereference an array.
@list = @$arrayref; Similar for hashes.

69. How do I do for each element in an array?
Ans: #!/usr/bin/perl –w
@homeRunHitters = (‘McGwire’, ‘Sosa’, ‘Maris’, ‘Ruth’);
Foreach (@homeRunHitters) { 
              print “$_ hit a lot of home runs in one year\n”;
}

70. How do I replace every character in a file with a comma?
Ans: perl -pi.bak -e ‘s/\t/,/g’ myfile.txt

71. What is the easiest way to download the contents of a URL with Perl?
Ans: Once you have the libwww-perl library, LWP.pm installed, the code is this:
#!/usr/bin/perl
use LWP::Simple;
$url = get ‘http://www.websitename.com/’;

72. How to concatenate strings in Perl?
Ans: Through . operator.

73. How do I read command-line arguments with Perl? Ans: With Perl, command-line arguments are stored in the array named @ARGV.
$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.
$#ARGV is the subscript of the last element of the @ARGV array, so the number of
arguments on the command line is $#ARGV + 1. Here’s a simple program:
#!/usr/bin/perl
$numArgs = $#ARGV + 1;
print “thanks, you gave me $numArgs command-line arguments.\n”;
foreach $argnum (0 .. $#ARGV) { 
         print “$ARGV[$argnum]\n”;
}

74. Assume that $ref refers to a scalar, an array, a hash or to some nested data structure.
Explain the following statements:
Ans: $$ref;                        # returns a scalar
$$ref[0];                          # returns the first element of that array
$ref- > [0];                       # returns the first element of that array
@$ref;                             # returns the contents of that array, or number of elements, in scalar context
$&$ref;                            # returns the last index in that array
$ref- > [0][5];                  # returns the sixth element in the first row
@{$ref- > {key}}            # returns the contents of the array that is the value of the key “key”

75. Perl uses single or double quotes to surround a zero or more characters. Are the single(‘ ‘) or double quotes (” “) identical?
Ans: They are not identical. There are several differences between using single quotes and double quotes for strings. 
1. The double-quoted string will perform variable interpolation on its contents. That is, any variable references inside the quotes will be replaced by the actual values. 
2. The single-quoted string will print just like it is. It doesn’t care the dollar signs. 
3. The double-quoted string can contain the escape characters like newline, tab, carraige return, etc. 
4. The single-quoted string can contain the escape sequences, like single quote, backward slash, etc.

76. How many ways can we express string in Perl?
Ans: Many. 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)

77. How do you give functions private variables that retain their values between calls? Ans: 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.

78. Explain the difference between the following in Perl: $array[3] vs. $array->[3] Ans: Because Perl’s basic data structure is all flat, references are the only way to build complex structures, which means references can be used in very tricky ways. This question is easy, though. In $array[3], “array” is the (symbolic) name of an array (@array) and $array[3] refers to the 4th element of this named array. In $array->[3], “array” is a hard reference to a (possibly anonymous) array, i.e., $array is the reference to
this array, so $array->[3] is the 4th element of this array being referenced.


79. How to remove duplicates from an array? Ans. There is one simple and elegant solution for removing duplicates from a list in PERL
@array = (2,4,3,3,4,6,2);
my %seen = ();
my @unique = grep { ! $seen{ $_ }++ }
@array;
print “@unique”;


No comments: