Thursday, June 28, 2012

Perl Interview Questions Part 10

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

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

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

Q:What is the easiest way to download the contents of a URL with Perl?
A: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/’;
 
Q:What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?
A
: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.

Q:If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{“Foo::”.EXPR}?
A:
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.