Set - 3

Question 1 :

How to concatenate strings with Perl? 

Answer :

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


Question 2 :

How do I read command-line arguments with Perl?

Answer :

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:

$numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";
foreach $argnum (0 .. $#ARGV) {
	print "$ARGV[$argnum]\n";


Question 3 :

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

Answer :

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.

Question 4 :

What happens to objects lost in "unreachable" memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), \$ap ]; }' ?

Answer :

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.

Question 5 :

Assume that $ref refers to a scalar, an array, a hash or to some nested data structure. Explain the following statements:

Answer :

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