Set - 1

Question 16 :

What is the output of the following Perl program?

$p1 = "prog1.java";
$p1 =~ s/(.*)\.java/$1.cpp/;
print "$p1\n";

 

Answer :

prog1.cpp


Question 17 :

Why aren't Perl's patterns regular expressions?

Answer :

Because Perl patterns have backreferences.
A regular expression by definition must be able to determine the next state in the finite automaton without requiring any extra memory to keep around previous state. A pattern /([ab]+)c\1/ requires the state machine to remember old states, and thus disqualifies such patterns as being regular expressions in the classic sense of the term.


Question 18 :

What does Perl do if you try to exploit the execve(2) race involving setuid scripts?

Answer :

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.


Question 19 :

How do I do < fill-in-the-blank > for each element in a hash?

Answer :

Here's a simple technique to process each element in a hash:

#!/usr/bin/perl -w
%days = (
	'Sun' =>'Sunday',
	'Mon' => 'Monday',
	'Tue' => 'Tuesday',
	'Wed' => 'Wednesday',
	'Thu' => 'Thursday',
	'Fri' => 'Friday',
	'Sat' => 'Saturday' 
);

foreach $key (sort keys %days) {
	print "The long name for $key is $days{$key}.\n";
}

 


Question 20 :

How do I sort a hash by the hash key? 

Answer :

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 "\n\tGRADES SORTED BY STUDENT NAME:\n";
foreach $key (sort (keys(%grades))) {
	print "\t\t$key \t\t$grades{$key}\n";
}

The output of this program looks like this:

GRADES SORTED BY STUDENT NAME:
al 63
chrisy 96
jane 79
kim 96
rocky 87