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>; 

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


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() );


Question 6 :

Why does Perl not have overloaded functions? 

Answer :

Because you can inspect the argument count, return context, and object types all by yourself.
In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they're references and simple pattern matching like /^\d+$/ otherwise. In languages like C++ where you can't do this, you simply must resort to overloading of functions.

Question 7 :

What does read() return at end of file? 

Answer :

A defined (but false) 0 value is the proper indication of the end of file for read() and sysread().

Question 8 :

What does `new $cur->{LINK}' do? (Assume the current package has no new() function of its own.)

Answer :


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\n"' 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.

Question 9 :

How do I sort a hash by the hash value? 

Answer :

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,

foreach $key (sort hashValueAscendingNum (keys(%grades))) {
	print "\t\t$grades{$key} \t\t $key\n";

foreach $key (sort hashValueDescendingNum (keys(%grades))) {
	print "\t\t$grades{$key} \t\t $key\n";


Question 10 :

How to read file into hash array ?

Answer :

open(IN, "<name_file")
or die "Couldn't open file for processing: $!";
while (<IN>) {
	$hash_table{$_} = 0;
close IN;
print "$_ = $hash_table{$_}\n" foreach keys %hash_table;


Question 11 :

How do you find the length of an array? 

Answer :



Question 12 :

What value is returned by a lone `return;' statement?

Answer :

The undefined value in scalar context, and the empty list value () in list context.
This way functions that wish to return failure can just use a simple return without worrying about the context in which they were called.

Question 13 :

What's the difference between /^Foo/s and /^Foo/?

Answer :

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.

Question 14 :

Does Perl have reference type?

Answer :

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.

Question 15 :

How to dereference a reference?

Answer :

There are a number of ways to dereference a reference.
Using two dollar signs to dereference a scalar.
$original = $$strref;
Using @ sign to dereference an array.
@list = @$arrayref;
Similar for hashes.

Question 16 :

What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?

Answer :

length() is a built-in prototyped as sub length($), and a scalar prototype silently changes aggregates into radically different forms. The scalar sense of a hash is false (0) if it's empty, otherwise it's a string representing the fullness of the buckets, like "18/32" or "39/64". The length of that string is likely to be 5. Likewise, `length(@a)' would be 2 if there were 37 elements in @a.

Question 17 :

If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{"Foo::".EXPR}?

Answer :

The second is disallowed under `use strict "refs"'.
Dereferencing a string with *{"STR"} is disallowed under the refs stricture, although *{STR} would not be. This is similar in spirit to the way ${"STR"} is always the symbol table variable, while ${STR} may be the lexical variable. If it's not a bareword, you're playing with the symbol table in a particular dynamic fashion.

Question 18 :

How do I do < fill-in-the-blank > for each element in an array?

Answer :

#!/usr/bin/perl -w
@homeRunHitters = ('McGwire', 'Sosa', 'Maris', 'Ruth');
foreach (@homeRunHitters) {
	print "$_ hit a lot of home runs in one year\n";


Question 19 :

How do I replace every <TAB> character in a file with a comma?

Answer :

perl -pi.bak -e 's/\t/,/g' myfile.txt 


Question 20 :

What is the easiest way to download the contents of a URL with Perl? 

Answer :

Once you have the libwww-perl library, installed, the code is this:

use LWP::Simple;
$url = get '';