Thursday, June 28, 2012

Perl Interview Questions Part 9

Q:How to concatenate strings with Perl?
A: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”;

Q:Perl uses single or double quotes to surround a zero or more characters. Are the single(‘ ‘) or double quotes (” “) identical?
A
: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.

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

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

No comments:

Post a Comment