Perl’s Darker Corners

Perl’s designers have stated that their philosophy in designing Perl is “There’s more than one way to do it.” My philosophy is a little different: “There is only one clearest way to do it.”

Unfortunately, if you examine some of the existing Perl scripts, you’ll discover that Perl has a very rich and sometimes confusing set of syntax elements. This section describes some of the slightly more obscure statements so that you’ll know what they do when you come across them.

The unless Statement

The unless statement is a shorthand for if not. For example, the following two statements are the same:

if (not defined ($title)) 
unless (defined ($title))

But why use two different words (unless and if) where one will do? There is no need for you to remember both of them. Just stick with the if not, and don’t worry about the unless.

The Dangling if and unless Statements

Normally the if and the unless statements precede the statements they control; but Perl lets you use the if and unless statements as a sort of postscript. For example, the following statement prints a debug message if the variable $debug is true:

print "The current file is $file
" if ($debug);

This is the equivalent of saying

if ($debug) {
    print "The current file is $file
"; 
}

The dangling if syntax can be a bit confusing. It’s like saying “I want you to perform this operation, but maybe not.” Same thing goes for the dangling unless. I suggest you stick to the traditional if. It might seem boring, but you’ll make your code clear and easy to understand for other programmers.

The __DATA__ File

A Perl program normally ends when you read the end of the file. You can, however, put in a special directive:

__DATA__

This directive tells Perl that what follows is not a part of the script but is a special place in your script for your data that can be read as an ordinary file using the <DATA> file handle.

For example:

use strict; 
use warnings; 

while (<DATA>) {
    print $_; 
} 
__DATA__ 
Hello, this is the data file 
and it will be printed by this program.

Note that there’s nothing that you can do with a data file that can’t be done with a proper set of initialization statements.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset