Set - 2

Question 1 :

How do you print out the next line from a filehandle with all its bytes reversed?

Answer :

print scalar reverse scalar <FH>
Surprisingly enough, you have to put both the reverse and the <FH> into scalar context separately for this to work.


Question 2 :

How do I send e-mail from a Perl/CGI program on a Unix system?

Answer :

Sending e-mail from a Perl/CGI program on a Unix computer system is usually pretty simple. Most Perl programs directly invoke the Unix sendmail program. We'll go through a quick example here.
Assuming that you've already have e-mail information you need, such as the send-to address and subject, you can use these next steps to generate and send the e-mail message:

# the rest of your program is up here ...
open(MAIL, "|/usr/lib/sendmail -t");
print MAIL "To: $sendToAddress\n";
print MAIL "From: $myEmailAddress\n";
print MAIL "Subject: $subject\n";
print MAIL "This is the message body.\n";
print MAIL "Put your message here in the body.\n";
close (MAIL);

 


Question 3 :

How to read from a pipeline with Perl?

Answer :

Example 1: 

To run the date command from a Perl program, and read the output
of the command, all you need are a few lines of code like this: 

open(DATE, "date|"); 
$theDate = <DATE>; 
close(DATE); 

The open() function runs the external date command, then opens a file handle DATE to the output of the date command. 
Next, the output of the date command is read into the variable $theDate through the file handle DATE.

Example 2:

The following code runs the "ps -f" command, and reads the output:

open(PS_F, "ps -f|"); 
while (<PS_F>) { 
	($uid,$pid,$ppid,$restOfLine) = split; 
	# do whatever I want with the variables here ... 
} 
close(PS_F);

 


Question 4 :

Why is it hard to call this function: sub y { "because" } 

Answer :

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].


Question 5 :

What does `$result = f() .. g()' really return?

Answer :

False so long as f() returns false, after which it returns true until g() returns true, and then starts the cycle again.
This is scalar not list context, so we have the bistable flip-flop range operator famous in parsing of mail messages, as in `$in_body = /^$/ .. eof()'. Except for the first time f() returns true, g() is entirely ignored, and f() will be ignored while g() later when g() is evaluated. Double dot is the inclusive range operator, f() and g() will both be evaluated on the same record. If you don't want that to happen, the exclusive range operator, triple dots, can be used instead. For extra credit, describe this:

$bingo = ( a() .. b() ) ... ( c() .. d() );