Thursday, June 28, 2012

Perl Interview Questions Part 4

Q:How do you print out {the next|the following} line {from a|from the} filehandle with all its bytes reversed?
A:print scalar reverse scalar <FH>
Surprisingly enough, {you have to|you need to} put both the reverse and the <FH> into scalar context separately for this to work.


Q:What does Perl do if you try to exploit the execve(2) race involving setuid scripts?
A:Sends mail to root and exits.
It has been said that all programs advance to the point of being able to automatically read mail. While not quite at that point (well, without having a module loaded), Perl does at least automatically send it.
Q:Why is it hard to call this function: sub y { “because” }
A:Because y is a kind of quoting operator.
The y/// operator is the sed-savvy synonym for tr///. That means y(3) would be like tr(), which would be looking for a second string, as in tr/a-z/A-Z/, tr(a-z)(A-Z), or tr[a-z][A-Z].


Q:How do I sort a hash by the hash key?
A:Suppose we have a class of five students. Their names are kim, al, rocky, chrisy, and jane.Here’s a test program that prints the contents of the grades hash, sorted by student name:
#!/usr/bin/perl -w
%grades = (
kim => 96,
al => 63,
rocky => 87,
chrisy => 96,
jane => 79,
);
print “SORTED BY STUDENT NAME:”;
foreach $key (sort (keys(%grades))) {
print “$key $grades{$key}”;
}
The output of this program looks like this:
GRADES SORTED BY STUDENT NAME:
al 63
chrisy 96
jane 79
kim 96
rocky 87
}

No comments:

Post a Comment