Thursday, June 28, 2012

Perl Interview Questions Part 6

Q:What’s the difference between /^Foo/s and /^Foo/?
A
:The second would match Foo other than at the start of the record if $* were set.
The deprecated $* flag does double duty, filling the roles of both /s and /m. By using /s, you suppress any settings of that spooky variable, and force your carets and dollars to match only at the ends of the string and not at ends of line as well — just as they would if $* weren’t set at all.

Q:Does Perl have reference type?
A
:Yes. Perl can make a scalar or hash type reference by using backslash operator.
For example
$str = “here we go”; # a scalar variable
$strref = \$str; # a reference to a scalar
@array = (1..10); # an array
$arrayref = \@array; # a reference to an array
Note that the reference itself is a scalar.

Q:How do I send e-mail from a Perl/CGI program on a Unix system?
A
: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);

Q:How to read file into hash array ?
A
:open(IN, “<name_file”)
or die “Couldn’t open file for processing: $!”;
while (<IN>) {
chomp;
$hash_table{$_} = 0;
}
close IN;
print “$_ = $hash_table{$_}\n” foreach keys %hash_table;

Q:How to read from a pipeline with Perl
A
: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);

No comments:

Post a Comment