Time To Earn

Saturday, November 16, 2013

Perl Most Ask Questions



What value is returned by a lone `return;' statement?
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.

What's the difference between /^Foo/s and /^Foo/?
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.

Does Perl have reference type?
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.

How to dereference a reference?
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.

What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?
5
length() is a built-in prototyped as sub length($), and a scalar prototype silently changes aggregates into radically different forms. The scalar sense of a hash is false (0) if it's empty, otherwise it's a string representing the fullness of the buckets, like "18/32" or "39/64". The length of that string is likely to be 5. Likewise, `length(@a)' would be 2 if there were 37 elements in @a.

If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{"Foo::".EXPR}?
The second is disallowed under `use strict "refs"'.
Dereferencing a string with *{"STR"} is disallowed under the refs stricture, although *{STR} would not be. This is similar in spirit to the way ${"STR"} is always the symbol table variable, while ${STR} may be the lexical variable. If it's not a bareword, you're playing with the symbol table in a particular dynamic fashion.

How do I do < fill-in-the-blank > for each element in an array?
#!/usr/bin/perl -w
@homeRunHitters = ('McGwire', 'Sosa', 'Maris', 'Ruth');
foreach (@homeRunHitters) {
print "$_ hit a lot of home runs in one year\n";
}

How do I replace every <TAB> character in a file with a comma?

perl -pi.bak -e 's/\t/,/g' myfile.txt

What is the easiest way to download the contents of a URL with Perl?

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/';

How to concatenate strings with Perl?

Method #1 - using Perl's dot operator:
$name = 'checkbook';
$filename = "/tmp/" . $name . ".tmp";

Method #2 - using Perl's join function
$name = "checkbook";
$filename = join "", "/tmp/", $name, ".tmp";

Method #3 - usual way of concatenating strings
$filename = "/tmp/${name}.tmp";

How do I read command-line arguments with Perl?

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


When would `local $_' in a function ruin your day?
When your caller was in the middle for a while(m//g) loop
The /g state on a global variable is not protected by running local on it. That'll teach you to stop using locals. Too bad $_ can't be the target of a my() -- yet.

What happens to objects lost in "unreachable" memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), \$ap ]; }' ?
Their destructors are called when that interpreter thread shuts down.
When the interpreter exits, it first does an exhaustive search looking for anything that it allocated. This allows Perl to be used in embedded and multithreaded applications safely, and furthermore guarantees correctness of object code.

Assume that $ref refers to a scalar, an array, a hash or to some nested data structure. Explain the following statements:
$$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"


How do you match one letter in the current locale?
/[^\W_\d]/
We don't have full POSIX regexps, so you can't get at the isalpha() <ctype.h> macro save indirectly. You ask for one byte which is neither a non-alphanumunder, nor an under, nor a numeric. That leaves just the alphas, which is what you want.

How do I print the entire contents of an array with Perl?
To answer this question, we first need a sample array. Let's assume that you have an array that contains the name of baseball teams, like this:
@teams = ('cubs', 'reds', 'yankees', 'dodgers');
If you just want to print the array with the array members separated by blank spaces, you can just print the array like this:
@teams = ('cubs', 'reds', 'yankees', 'dodgers');
print "@teams\n";
But that's not usually the case. More often, you want each element printed on a separate line. To achieve this, you can use this code:
@teams = ('cubs', 'reds', 'yankees', 'dodgers');
foreach (@teams) {
print "$_\n";
}

Perl uses single or double quotes to surround a zero or more characters. Are the single(' ') or double quotes (" ") identical?
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.

How many ways can we express string in Perl?
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)

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


------------------------------------

1) What are the two different types of data perl handles?
Perl handles two types of data they are
(i) Scalar Variables and
(ii) Lists
Scalar variables hold a single data item whereas lists hold multiple data items.

2) What are scalar variables?
Scalar variables are what many programming languages refer to as simple variables. They hold a single data item, a number, a string, or a perl reference. Scalars are called scalars to differentiate them from constructs that can hold more than one item, like arrays.

3) Explain about lists?
A list is a construct that associates data elements together and you can specify a list by enclosing those elements in parenthesis and separating them with commas. They could themselves be arrays, hashes or even other lists. Lists do not have a specific list data type.

4) 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.
5) Explain about an ivalue?
An ivalue is an item that can serve as the target of an assignment. The term I value originally meant a “left value”, which is to say a value that appears on the left. An ivalue usually represents a data space in memory and you can store data using the ivalues name. Any variable can serve as an ivalue.
6) How does a “grep” function perform?
Grep returns the number of lines the expression is true. Grep returns a sublist of a list for which a specific criterion is true. This function often involves pattern matching. It modifies the elements in the original list.
7) Explain about Typeglobs?
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.
8) Is there any way to add two arrays together?
Of course you can add two arrays together by using push function. The push function adds a value or values to the end of an array. The push function pushes the values of list onto the end of the array. Length of an array can be increased by the length of list.
9) How to use the command shift?
Shift array function shifts off the first value of the array and returns it, thereby shortening the array by one element and moving everything from one place to the left. If you don’t specify an array to shift, shift uses @ ARGV, the array of command line arguments passed to the script or the array named @-.
10) What exactly is grooving and shortening of the array?
You can change the number of elements in an array simply by changing the value of the last index of/in the array $#array. In fact, if you simply refer to a non existent element in an array perl extends the array as needed, creating new elements. It also includes new elements in its array.
11) What are the three ways to empty an array?
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.

12) How do you work with array slices
An array slice is a section of an array that acts like a list, and you indicate what elements to put into the slice by using multiple array indexes in square brackets. By specifying the range operator you can also specify a slice.
13) What is meant by splicing arrays explain in context of list and scalar.
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.
14) What are the different types of perl operators?
There are four different types of perl operators they are
(i) Unary operator like the not operator
(ii) Binary operator like the addition operator
(iii) Tertiary operator like the conditional operator
(iv) List operator like the print operator
15) Which has the highest precedence, List or Terms? Explain?
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.
16) What is a short circuit operator?
The C-Style operator, ll, 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.

17) What are the different forms of goto in perl? Explain?
The three forms of goto are as follows. They are
(i) Goto label
(ii) Goto name
(iii) Goto expr
The first form, goto LABEL, transfers execution to the statement labeled LABEL. The second form, goto EXPR, expects EXPR to evaluate to a label. The last form goto &name is used with subroutines. This goto statement is used only when there is a necessity as it can create havoc in a program.
18) What are the different types of eval statements?
There are two different types of eval statements they are eval EXPR and eval BLOCK. Eval EXPR executes an expression and eval BLOCK executes BLOCK. Eval Block executes an entire block, BLOCK. First one is used when you want your code passed in the expression and the second one is used to parse the code in the block.
19) Determine the difference between my and local?
The fundamental difference between my and local is that my creates a new variable, whereas local saves a copy of an existing variable.
20) Explain about returning values from subroutines (functions)?
The return value of the subroutine is the value of the last expression evaluated or you can explicitly use a return statement to exit the subroutine specifying the return value. That return value is evaluated in the appropriate content depending on the content of the subroutine call.


--------------------------------

   1. Does Perl have reference type?

   2. How do I do < fill-in-the-blank > for each element in a hash?

   3. How do I do < fill-in-the-blank > for each element in an array?

   4. How do I do fill_in_the_blank for each file in a directory?

   5. How do I generate a list of all .html files in a directory?

   6. How do I print the entire contents of an array with Perl?



      -- Useful EBooks --

      How To Naturally Regrow Lost Hair


   7. How do I read command-line arguments with Perl?

   8. How do I replace every character in a file with a comma?

   9. How do I send e-mail from a Perl/CGI program on a Unix system?

  10. How do I set environment variables in Perl programs?

  11. How do I sort a hash by the hash key?

  12. How do I sort a hash by the hash value?

  13. How do you find the length of an array?

  14. How do you give functions private variables that retain their values between calls?

  15. How do you match one letter in the current locale?



      -- Useful EBooks --

      Weird Tricks to Lose Your Abdominal Fat


  16. How do you print out the next line from a filehandle with all its bytes reversed?

  17. How many ways can we express string in Perl?

  18. How to concatenate strings with Perl?

  19. How to dereference a reference?

  20. How to open and read data files with Perl

  21. How to read file into hash array ?

  22. How to read from a pipeline with Perl

  23. How to turn on Perl warnings? Why is that important?

  24. If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{"Foo::".EXPR}?

  25. Perl uses single or double quotes to surround a zero or more characters. Are the single(' ') or double quotes (" ") identical?

  26. What are scalar data and scalar variables?

  27. What does Perl do if you try to exploit the execve(2) race involving setuid scripts?

  28. What does `$result = f() .. g()' really return?

  29. What does `new $cur->{LINK}' do? (Assume the current package has no new() function of its own.)

  30. What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?

  31. What does read() return at end of file?

  32. What happens to objects lost in "unreachable" memory..... ?

  33. What happens when you return a reference to a private variable?

  34. What is the easiest way to download the contents of a URL with Perl?

  35. What value is returned by a lone `return;' statement?

  36. What's the difference between /^Foo/s and /^Foo/?

  37. When would `local $_' in a function ruin your day?

  38. Which of these is a difference between C++ and Perl?

  39. Why aren't Perl's patterns regular expressions?

  40. Why do you use Perl?

  41. Why does Perl not have overloaded functions?

  42. Why is it hard to call this function: sub y { "because" }

  43. Why should I use the -w argument with my Perl programs?

-----------------------

Question #2: Write a regular expression which matches a email address

Answer: This is very tricky question. Matching emails is not as trivial as it seems and the answer can be as simple as \w+@\w+\.[\w]{3}  or as messy as ^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}

Remember, it is interview question, not production code. So, be simple. I always recommend starting with basics:
\w+@\w+\.[\w]{3}

Then explain its limitations and give couple examples there the pattern would give false positive or false negative results. (such as test@test.111). From my experience, usually it is more than enough to impress interviewer.  From the other side, you always can iteratively enhance this pattern engaging interviewer into the conversation giving you the chance to showcase your knowledge.oo/?

  37. When would `local $_' in a function ruin your day?

  38. Which of these is a difference between C++ and Perl?

  39. Why aren't Perl's patterns regular expressions?

  40. Why do you use Perl?

  41. Why does Perl not have overloaded functions?

  42. Why is it hard to call this function: sub y { "because" }

  43. Why should I use the -w argument with my Perl programs?

-----------------------

Question #2: Write a regular expression which matches a email address

Answer: This is very tricky question. Matching emails is not as trivial as it seems and the answer can be as simple as \w+@\w+\.[\w]{3}  or as messy as ^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}

Remember, it is interview question, not production code. So, be simple. I always recommend starting with basics:
\w+@\w+\.[\w]{3}


Then explain its limitations and give couple examples there the pattern would give false positive or false negative results. (such as test@test.111). From my experience, usually it is more than enough to impress interviewer.  From the other side, you always can iteratively enhance this pattern engaging interviewer into the conversation giving you the chance to showcase your knowledge. 

No comments:

Post a Comment