Thursday, June 28, 2012

Perl Interview Questions Part 7

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

Q:How do you match one letter in the current locale?
A:We do not have full POSIX regexps, which means you can not 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.

Q:What does `new $cur->LINK’ do? (Assume the current package has no new() function of its own.)
A:$cur->new()->LINK
The indirect object syntax only has a single token lookahead. That means if new() is a method, it only grabs the very next token, not the entire following expression.
This is why `new $obj[23] arg’ does’t work, as well as why `print $fh[23] “stuff”‘ does’t work. Mixing notations between the OO and IO notations is perilous. If you always use arrow syntax for method calls, and nothing else, you’ll not be surprised.

Q:How do I sort a hash by the hash value?
A: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”;
}

No comments:

Post a Comment