ASP and ADO with Activeperl with CD-ROM

( 1 )

Overview

This book/CD package gets you up to speed on all of ActivePerl's features in no time. Tobias Martinsson introduces the tools included in ActivePerl and walks you through installation and configuration, then gives you an overview of the syntax, variables, functions, control structures, and regular expressions of Perl and PerlScript. Chapters on ASP and ADO demystify the jargon, components, and concepts behind the technologies, and then focus on the objects and functionalities they can add to your programs. ...
See more details below
Available through our Marketplace sellers.
Other sellers (Paperback)
  • All (14) from $1.99   
  • New (3) from $38.56   
  • Used (11) from $1.99   
Close
Sort by
Page 1 of 1
Showing All
Note: Marketplace items are not eligible for any BN.com coupons and promotions
$38.56
Seller since Tue Oct 07 09:35:53 EDT 2014

Feedback rating:

(294)

Condition:

New — never opened or used in original packaging.

Like New — packaging may have been opened. A "Like New" item is suitable to give as a gift.

Very Good — may have minor signs of wear on packaging but item works perfectly and has no damage.

Good — item is in good condition but packaging may have signs of shelf wear/aging or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Acceptable — item is in working order but may show signs of wear such as scratches or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Used — An item that has been opened and may show signs of wear. All specific defects should be noted in the Comments section associated with each item.

Refurbished — A used item that has been renewed or updated and verified to be in proper working condition. Not necessarily completed by the original manufacturer.

New
Brand New Item.

Ships from: Chatham, NJ

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
$57.45
Seller since Tue Oct 07 09:38:39 EDT 2014

Feedback rating:

(58)

Condition: New
0471383147 THIS BOOK IS IN STOCK & WILL SHIP SAMEDAY!BRAND NEW,UNREAD COPY IN PERFECT CONDITION.MAYBE PUBLISHER OVERSTOCK ANDHAVE SLIGHT SHELF WEAR.FREE TRACKING NUMBER PROVIDED ... IMMEDIATELY UPON PURCHASE YOU CAN TRACK ORDER WITH EASE. WE SHIP 6 DAYS A WEEK TWICE A DAY! GUARANTEED A++CUSTOMER SERVICE. Read more Show Less

Ships from: Northridge, CA

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
$65.00
Seller since Tue Oct 07 09:37:03 EDT 2014

Feedback rating:

(184)

Condition: New
Brand new.

Ships from: acton, MA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
Page 1 of 1
Showing All
Close
Sort by
Sending request ...

Overview

This book/CD package gets you up to speed on all of ActivePerl's features in no time. Tobias Martinsson introduces the tools included in ActivePerl and walks you through installation and configuration, then gives you an overview of the syntax, variables, functions, control structures, and regular expressions of Perl and PerlScript. Chapters on ASP and ADO demystify the jargon, components, and concepts behind the technologies, and then focus on the objects and functionalities they can add to your programs. Extensive code examples teach you how and where to use the objects, events that trigger them, and how to program with optimal performance in mind. And as a valuable reference, the author provides detailed tables on each object and its associated task options throughout the book to help you harness the full power of ASP and ADO.
Read More Show Less

Editorial Reviews

Booknews
Written for Windows developers, this guide walks through ActivePerl installation and configuration, then overviews the syntax, variables, functions, control structures, and regular expressions of Perl and PerlScript. Chapters on ASP and ADO demystify the jargon, components, and concepts behind the technologies, then focus on the objects and functionalities. The CD-ROM contains ActivePerl Build 522 and scripts. Annotation c. Book News, Inc., Portland, OR (booknews.com)
Read More Show Less

Product Details

  • ISBN-13: 9780471383147
  • Publisher: Wiley
  • Publication date: 4/4/2000
  • Edition description: BK& CD ROM
  • Edition number: 1
  • Pages: 290
  • Product dimensions: 7.54 (w) x 9.21 (h) x 0.73 (d)

Table of Contents

Acknowledgments
Introduction
Ch. 1 Active Server Pages 1
Ch. 2 Perl Programming Basics 19
Ch. 3 Elevating the Stateless Internet 69
Ch. 4 Practical Active Server Pages 81
Ch. 5 The Special Utility Objects 107
Ch. 6 Universal Data Access 115
Ch. 7 Database Programming in ADO 139
Ch. 8 The Heart of ADO 163
Ch. 9 Fast Queries with the Command Object 227
Ch. 10 A Natural Systems Record 235
Ch. 11 Working the Stream of Data 245
App. A Bag of Scripts 251
App. B What's on the CD-ROM 263
App. C The HTTP Status Description 267
App. D Content Types 269
App. E ActivePerl Activity on the Web 271
Glossary 273
Index 279
Read More Show Less

First Chapter

NOTE: The Figures and/or Tables mentioned in this sample chapter do not appear on the Web.

Perl Programming Basics


CHAPTER 2

The Practical Extraction and Report Language (Perl) has collected some of the most powerful features of several languages. Its functions are very wide in spectrum, and the features have grown since the first release of Perl and turned into features for which programmers look to Perl. While many of the built-in functions provide optimized routines for common programming tasks instead of forcing the programmer to reinvent the wheel, others lend supreme yet simple functionality for the simple tasks. In addition to all this, Perl supports both a classic model and an object-oriented model of programming. Whereas both computer science today and a number of programming languages are devoted to object-oriented programming, Perl does not make one school of programming prevalent.

Before getting started, you should be aware that because Perl is a rather free-form language, learning the basics becomes only the beginning. There are many different ways of writing Perl code that acts the same but certainly does not look the same; thus the approach, style, and structure of writing the code quickly become a personal preference. The free-form approach of programming Perl, however, does not mean that the language in itself is a quick hack (although it can be used to write quick hacks). Instead, the freedom to write code that is either simplistic or complex is one of its major features.

In any case, whether the Perl code is short and cryptic or long and well described, this is an introduction to the functions and methodologies of Perl and how they can be applied to describe the language. How you use it is between you and Perl-- very negotiable but you must start with the Perl programming basics.

Getting a Head Start with Perl

In this section, we begin the journey into Perl by exploring the components included in the ActivePerl software package. It is important to first learn a few simple basics on what you can do with the tools provided with ActivePerl, because they come in handy when you encounter potential problems in a programming project. These tools greatly enhance the first few weeks of the Perl experience and speed up the process of learning while providing a solid foundation for the future.

In addition to how these tools are used to leverage the surroundings of Perl, the basics of programming Perl will be covered with discussion and examples. No familiarity with Perl or any other programming language is assumed-- although it doesn't hurt-- for anything that is presented, so please take your time, read things over, and try everything out on your local installation if this is your first experience with Perl.

In the Programmer's Toolbox . . .

A number of components are installed with ActivePerl, and quite a few of them quickly become familiar. Whether you need to turn to these tools for programming advice, development of skills, or means of extending Perl, we will concentrate on getting the two most important tools surrounding Perl going. They provide all of these functions, and they are:

  • The Perl documentation
  • Perl Package Manager

The ActivePerl documentation contains the core Perl documentation, a priceless set of documents that cover absolutely all earthly knowledge about Perl. It is the tool for actual programming problems and finding answers to questions on the scale from trivial to tough. The second tool is Perl Package Manager, a package management application. Perl Package Manager makes it more than easy to install additional functionality for Perl by downloading packages, or prebuilt libraries of code, from remote locations by automating the task of package management.

The ActivePerl Documentation

A giant collection of documents, the ActivePerl documentation contains important contributions from several authors. Each document generally provides advice and instructions on a specific set of topics, and the documentation is divided into the following sections:

  • Getting Started includes the welcome page, installation instructions, and some history on the evolution of Perl through time.
  • ActivePerl Components discusses, among other things, the various components that can be installed with ActivePerl and what their uses are.
  • ActivePerl FAQ contains frequently asked questions (FAQ) about Perl on Win32, how-to examples, and information on embedding Perl in applications written in other languages and extending Perl. It also covers automation of items such as Microsoft Office Excel spreadsheets.
  • Core Perl FAQ is the number one ranked spot for finding quick answers on the problems that occur when programming, and it has plenty of how-to documentation. It is quite extensive, so give it a chance in case of a problem because there is most likely documentation there. In addition, this section also includes comparisons between scripting languages, and the history and story behind Perl.
  • Core Perl Docs includes everything you need to become a Perl expert. It is a huge amount of documentation on literally everything about Perl.
  • Module Docs is the information about the installed root modules for Perl and how to use them. In addition, documentation for modules installed with Perl Package Manager will automatically be added to the same index. Each paper describes how to use the module that was added to the Perl installation.

Whenever You Need to Ask a Perl Question

When looking for answers to your Perl questions, it is not always easy to sift through the documentation by hand and find exactly the right paper. Simply opening the right window, finding the right window, or finding the right section can become somewhat time consuming. The remedy is a command-line tool named Perldoc (file name: perldoc. bat), which is available to make it first easier but most importantly quicker to look up topics in the documentation. The following example illustrates how Perldoc provides information about a built-in Perl function:

1. Enter the command prompt.

2. Enter Perldoc and you will see an index of available commands.

3. Enter Perldoc -h and you will get more extensive information on how to use the program.

4. Enter Perldoc -f my and a listing about the my function will be printed to the screen.

Without overly long searching, this approach rapidly provides, on the screen, the answer about what the my() function is meant for, including description, syntax, and further references.

While built-in functions provide definitive facts, this might not always be satisfying. In this case, when further information becomes necessary, Perldoc can be told how and where to search for your keywords. Specifying either one of the options at the command line uses this feature. For example, previously, the -f switch was used to declare that what we were looking for was a function. The available options are presented in Table 2.1.

Although its appearance is not very elegant and has no windows and buttons, Perldoc is really useful. It is advantageous not to have such controls as clickable buttons because the program executes faster, crashes less often than a browser, and provides quicker answers. In addition, it suits the preference of working against a black background in a dark room without the sun glaring at the monitor.

One word of notice, however: It is advisable to become familiar with the Perl documentation before using Perldoc. Browse around the papers on the local installation, and in that way you will quickly learn what documents it will search. There is a naming convention used for the documents that is worth getting friendly with:

  • Documents in the core Perl documentation begin with the letters perl, followed by an abbreviation that describes the topic of the document. For example perldoc, perldata will pull up the core documentation about data types in Perl.
  • Perl frequently asked questions are named with a number, so that perldoc perlfaq6 will retrieve the sixth FAQ.
  • The module docs are pulled up by entering perldoc modulename, thus the following commands are valid: perldoc Benchmark, perldoc attrs, and perldoc English.
  • The built-in functions of Perl are browsed by using the -f option, as previously seen, thus the following commands are valid: perldoc -f my, perldoc -f local, perldoc -f print.

All of this gives a general idea of what the Perl documentation includes, and makes it much easier to search the known territory.

In short, Perldoc is a powerful tool for finding quick, elaborate, and exact answers about Perl. It is superior to manually browsing the documentation by hand. However, it is necessary to become familiar with the documentation in order to use the full potential of Perldoc.

The Perl Package Manager

Not so long ago, extending the functionality of Perl was somewhat of a problem. For example, Perl could be extended to drawing graphics, sending e-mail, and managing Windows services, and understandably this made Perl the language of choice. As many experienced, though, it was an inconvenience to install modules to extend Perl's tool-box because it involved a lot of work.

For our convenience, ActiveState released Perl Package Manager (PPM). This solved the problems that many found with installing and managing modules, plus made module procedures very easy. Instead of being downloaded, upgraded, removed, or created by hand, a module is prepackaged for Perl Package Manager. After a module is completed for download, Perl Package Manager automates all the tasks so that virtually everyone can install the desired modules.

Why Bother Installing Modules?

In general, a module is installed for several reasons. Normally the reason is because a module gives some functionality, not provided by Perl's built-in functions, that you need for your script. There are two types of modules:

  • Modules that provide reusable code built on Perl functionality: For example, Perl scripts written to send e-mail and check e-mail are bundled into the Libnet package for this reason.
  • Modules that extend Perl with functionality written in C/ C++ or a mixture between C/ C++ and Perl: For example, the GD graphics library is a Perl port of a C graphics library that enables Perl to generate graphics on the fly.

A module has a number of characteristics and conventions. First, the file extension for a Perl module is always .pm. The .pm file may optionally autoload dynamically linked executables that it uses to extend its capacity.

Installing Modules with PPM

Perl Package Manager downloads modules that are located in a repository. The ActiveState repository is the default, and it is the location where the most popular modules are made available. It is pretty much configurable to suit your own needs, but let's first follow the next example either mentally or on the computer to see how it can be used.

1. Enter the command prompt.

2. Type ppm and hit enter.

3. A PPM shell opens, so enter help to see the available commands.

When asking PPM to bring up the help menu, the commands in Table 2.2 are the listed commands for PPM:

In the table, the commands are in their most simplistic form. Most can be extended, as will be shown, but let's begin with an example of how to install a package from the ActiveState repository.

When installing a package, you can (1) know the name of the package; (2) search for text that you know is in the name or is part of the abstract description of a package; or (3) list all available packages. In the example, the package named Libnet will be searched, found, and installed. Assuming that you are still in a PPM prompt, continue from the example.

1. Type search and wait for the result. After action 1, a whole list of packages flashes by on the screen. Did you catch any of it? Don't expect to. Depending on the version of Windows that you use, you might be fortunate enough to have the command prompt windows scrollable. If that is the case, you can easily scroll up the lines and see what all the available packages were. However, when you can't do that, you can specify the number of names to show and then pause the program until you press a key.

2. Type set more 3 and issue search once more. Action 2 will force the program to pause every third line. This is one way to locate the Libnet package successfully. Next, do the following:

3. Enter help query for options on how to retrieve information about packages.

4. Bring up the description for Libnet by typing query /abstract libnet, and it will tell you about the package, which is an application programming interface to a variety of Internet protocols. Essentially, the same information can be extracted by typing summary libnet.

5. Enter install libnet.

Installing a package with PPM is very easy and straightforward. The one thing to note, however, is that you will not be notified about the status of the installation until the package has been downloaded. The exception to this rule is if the package cannot be found, in which case PPM will notify you.

In order to customize some features of PPM, the set command has a number of variables that it is able to modify. The outcome is that some behavior in PPM is changed. Table 2.3 shows the arguments for the set command:

In general, Perl Package Manager will be installed with the best settings for your system. But, with all this in mind, what else is there to know about it? Table 2.4 gives more commands that can be used.

Examples of Modules

There are lots of modules. Following is a list of a few of them and what they are used for:

Libnet. Application programming interface to the most popular Internet protocols. Libnet enables you to send e-mail, check e-mail, use newsgroups, transfer files, and write software that uses any of the classes.

GD: graphics library. Generate graphics on the fly in Active Server Pages or other applications. Full support for graphics primitives, fonts, brushes, color palettes, and loading and saving of the images.

LWP: library for WWW access in Perl. Application programming interface to the World Wide Web. The classes and functions help you build WWW clients with support for most protocols, including HTTP, HTTPS, Gopher, news, and FTP, to name a few.

Win32 modules. Win32:: Internet implements the Win32 Internet APIs and provides object-oriented access to HTTP, FTP, and Gopher.

Many modules also give very powerful features at hand that are, if not fun, at least useful when developing client applications.

  • Win32:: OLE supports automation. It makes it easy to use Microsoft Office by automating Word, Excel, Access, and other products from Perl. It is also used by PerlScript, and its methods are well worth checking out.
  • Win32:: GUI makes the familiar windows graphical user interface (GUI) controls available for Perl. Full-blown GUI client applications can be written in Perl for Windows. The Tk module provides a non-Windows-look GUI.
  • Win32:: NetAdmin can be used by administrators who want to manage network groups and users with a few lines of Perl.

The Standard Perl Modules

The standard Perl modules (Table 2.5) are those that are installed with ActivePerl. The table of these modules contains a summary of each one. To learn more about a given functionality, enter perldoc modulename at the command prompt or browse in the online documentation.

Introduction to Programming Perl

Every introduction to a computer programming or scripting language must begin somewhere. Since most parts of a programming language are interconnected, it is very difficult to structure a tutorial perfectly. However, this chapter begins at one end and moves step by step to the other. A word of advice, however, is to skip sections that don't make sense-- because they will make sense later-- and read back over them when you know what you have learned.

Programmatical Grammar

In programming, the grammatical rules of a language are its syntax. The conventions of programming with Perl are simple:

1. A comment is indicated by a pound sign (#). It always runs to the end of the current line and it is always ignored by the Perl interpreter. The comments are used to describe the workings of the code, such as what information a variable holds or what a subroutine does, and also other items such as author, description, or product name. It is also a helpful inclusion for the next programmer who will look at or work with your code-- even if that programmer is you!

2. A line that starts with an equal sign (=) signals the start of a section of Plain Old Documentation (POD), which is a documentation format that can be embedded in code. Perl modules are generally documented in POD.

3. A simple statement, such as a call to a built-in function, ends with a semicolon (;). A simple statement normally executes a command, and the semicolon is the separator between statements. As a parallel, Visual Basic uses the new line metacharacter, which means that you hit the Enter key between statements, and C/ C++, like Perl, uses a semicolon for the purpose of separating simple statements.

4. A compound statement, or grouped series of instructions or commands-- also called a block-- is enclosed within curly braces ({}). A compound statement is a series of instructions, and it can also include other compound statements. In essence, compound statements are executed by a controlling statement that, for example, executes the block of code 10 times, executes it only if the given password was correct, or prints the contents of a file until the file has reached its end.

Scalar Variables

By means of in-memory storage of information, Perl provides the scalar variables to store information. Scalar variables are used to hold values and can be set at one point in the program and then retrieved, edited, or deleted at a later point. Moreover, there are three types of scalar variables that you can work with in Perl:

  • The scalar variable
  • The array of scalar variables
  • The associative array of scalar variables

When declaring a variable, it must be provided with its own identifier, which predicates what context it is stored in. Although every single variable in Perl is a scalar variable, the context determines what data type a given variable is and what operations can be performed on it. For example, a list of related scalar variables is commonly stored in an array, while a single value is held in a scalar variable. The data type identifier is a special character ($, @, or %), and following it is an identifier name that may contain letters, digits, and underscores up to a total of 251 characters. Keep in mind, though, that a name is case sensitive, so if a variable was named in all uppercase letters, it will not be found if the script tries to locate it by means of all lowercase letters. The same is true for any combination of upper-and lowercase letters that is used for naming and locating a variable. In general, it is common to begin a variable name with a letter or an underscore as the first character after the identifier, then follow this with any character. It is not, however, valid to follow a variable whose first character is a digit with characters other than digits. Variables that are not of the same type can share the same name without being mixed up, since the identifier type in the call for the variable will let Perl know which variable to get. Notice, however, that there are predefined variables for Perl's behavior whose names you do not want to use by mistake. Normally these special scalar variables are followed by special characters such as /, !, and [, so it is best to avoid using similar names when declaring variables.

In terms of identifier types, $ is the identifier for a scalar variable, @ for the array, and % for the associative array. The identifier type and identifier name are used when Perl locates the variable when it is called or when an operation is performed on the variable in the program. In addition, while some programming languages may require you to define the type of data and amount of the data that you want the variable to contain, Perl does not have such a requirement for its variables to work as expected. It simply has the scalar variable, and it can hold practically all data types. In this sense, Perl is somewhat different than many languages, but also much more simple to manage because it does not make you think about what data types you are using.

Finally, a scope can be used to define where the variable is accessed after it has been declared. In general, a variable that is declared without a scope is essentially accessible anywhere in the code, but as the code grows and is divided into subroutines, it becomes less and less practical not to declare it as private to one or several blocks of code. (A block of code is the commands that are enclosed by curly braces.) There are two kinds of scope:

Dynamic scope. A dynamically scoped variable is declared by the local() function and to begin with it is accessible within the block of code where it was declared. Moreover, if a subroutine (which is another block of code) is called from within its scope, the locally declared variable can be accessed in the called subroutine.

Lexical scope. The lexically scoped variable is declared with the my() function and can be used to keep a private variable. In Perl, most declared variables are declared with lexical scope. Its restriction is that it can only be accessed within the block of code in which it was declared.

In summary, when a variable is declared as just described, the type of variable is set by the type identifier that describes its context, and then it is followed by the name assigned to the variable. The name of the variable normally starts with a letter or an underscore, and then is followed by any combination of valid characters. However, a variable cannot be followed by anything but digits if the first character is a digit. When declared, the initial value of a declared variable is nothing, which in Perl is equal to undef. A variable, however, can have its value initialized at any point, including upon declaration, by following it with an equal sign (=) and the value to set. All of this is true for variables whose scope has been defined. Dynamic and lexical scope are used to make variables more accessible or less accessible to the right parts of the program. Later in the program, both the type identifier and the identifier name are used in the script to locate the variable and its value, provided that it is in the right scope when called.

The Scalar Variable

As the cornerstone of Perl, the scalar variable is the underlying placeholder of all entities. The scalar variable refers to a single value that either is numeric, a string of text, or a reference to another value. Thanks to this interoperability, numbers and strings are interchangeable and can transparently converse with each other.

You can declare the scalar variable anywhere in your program. It can be initialized with a value on the spot or assigned a value later in the program. Until it is assigned a value, however, it will be equal to "undef" or better known as a null value. In order to define a variable as a scalar, put the identifier type $ before the identifier name. Next, to assign a value, separate the value and variable with an equal sign. The following are all valid scalar variables with different types of values:

my $MyDoubleQuotedText = "Stuff";

my $MySingleQuotedText = 'Stuff';

my $MyNumber = 100;

my $MyFloat = 100.99;

my $MyReadableMillion = 1_ 000_ 000;

In the previous example, a variety of values were put into scalar variables, such as strings, integers, floating-point values, and a way of explicitly writing a large number readably by using the underscore (which by the way will not affect calculations). There is an upper limit to the size of the numbers a scalar is capable of storing (which few general scripts reach); the strings can be as long as the memory on the machine can handle. You can declare and assign values to more than one scalar on the same line by enclosing them within parentheses.

my ($ text, $twodigitnumber, $digit);

my ($ Text, $TwoDigitNumber, $Digit) = (' Hello', 34, 5);

As seen in the first example, strings can be enclosed within double quotes and single quotes. When you work with strings, whether you use double or single quotes for scalar values will matter.

In terms of text, the double-quoted string has many characteristics. It first of all allows you to embed white space such as new line characters, spaces, and tab characters into the string, which can be used for formatting the output. Second and more interestingly, enclosing a scalar value in double quotes will cause scalar variables to be interpreted as scalar values instead of text. If you include a variable within a double-quoted string, either deliberately or by mistake, it will register a value of what is represented instead of treating the variable name as plain text.

The following example demonstrates what is called variable interpolation -The two scalar variables within the double- quoted string are treated as scalar values.

my $What = "Ask";

my $Who = "Bob";

my $SayWhat = "$ What $Who \n"; # Prints "Ask Bob" and a newline

There are some things to beware of when using double-quoted strings. Data type identifiers, for example, are interpreted in double-quoted strings since you can use scalar variables. Moreover, control characters, which include all the data type identifiers, cannot be represented as literal characters if they are not escaped by explicitly telling the interpreter to treat them as characters without a meaning. The following is an occasion where a variable will not print the expected result:

my $EndResult = "$ 1,000"; # This will output ", 000"

As a remedy, the proper way to escape a control character or any other character is to put a backslash in front of it. Backslashing a character causes it to be treated as the plain character or text. On some common occasions, it is important to remember to escape the control characters. For example, when opening a file on the file system, each backslash in the file path must be escaped or else the file will not be found. The next example shows how to backslash by correcting the previous mistake:

my $EndResult = "\$ 1,000"; # This will output "$ 1,000"

In contrast to the flexibility of the double-quoted strings, the single-quoted string is much stricter. In a single-quoted string everything is treated as a pure textual representation, so neither white space nor scalar values will be treated as anything but pure textual characters. This eliminates the need for escaping characters, and provides a practical way of embedding double quotes, for example, within a string without making it unreadable by escaping every double quote.

my $SayHi = '$ Greet $Name \n'; #Outputs "$ Greet $Name \n"

On the topic of strings, it quite often becomes necessary to concatenate two or more strings-- in other words, to join the strings together into one single string. The dot operator is used to concatenate string values. For example:

The following example demonstrates concatenation where two scalars are combined into one new scalar variable

my ($ Say, $Who) = (" Take me to", "your leader");

my $MyMessage = $Say." ".$ Who."."; # "Take me to your leader";

However, recall that double quotes are allowed within single quotes. This is perfect for writing HTML in Active Server Pages or another application, but it does not allow scalar values to be interpolated. The solution is to concatenate these strings (or use single quotes in the HTML, although it would not serve this example):

print '< TD ALIGN=" LEFT"

BGCOLOR="# FFFFFF"> '.$ scalarString. '</ TD> ';

versus

print "< TD ALIGN=\" LEFT\"

BGCOLOR=\"# FFFFFF\">$ scalarString</ TD>";

Related Functions

uc(string)

Converts a string into a string of all uppercase letters.

$allLower = "hello";

$allUpper = uc($ allLower);

ucfirst(string)

Converts the first character of a string into an uppercase character.

$myName = "andreas";

$newName = ucfirst($ myName);

substr( string, offset [, length] [, replacement])

Returns a substring from string that is length long in characters and starts at the position offset. Offset is 0 by default, but if a negative number is used, then it starts from the right end and moves to the left. Replacement can be specified as the value with which to replace the extracted substring. Copy text from the original string:

$string = "abcdef";

$substring = substr($string, 0, 3);

print $string, "=", $substring;

To remove the substring from the original, one minor change is made:

$string = "abcdef";

$substring = substr($ string, 0, 3, undef);

print $string, "=", $substring;

index( string, substring [,start])

Returns the index of the first substring found in string. Start is 0 by default, and the method returns -1 if the substring is not found.

$string = "abcdefghi";

$index = index($ string, "efg", 0);

print $index;

rindex( string, substring [, start])

Same as the index function, except that it returns the last index of the string to match.

$string = "x_ x_ x_ x_ x_ x";

$index = rindex($ string, "_ x");

print $index;

ord( character)

Returns the character value of the first character in the given string, in this case a (although b and c are there):

$string = "abc";

print ord($ string);

length( string)

Returns the length in characters of the value of EXPR, or $_ if EXPR is not specified.

$string = "abc";

print length($ string);

lcfirst(string)

Returns a string of EXPR where the first letter is lowercase, or returns a string of $_ if EXPR is not specified where the first letter is lowercase.

$string = "Hello";

$string = lcfirst($ string);

print $string;

lc( string)

Returns an all-lowercase string of EXPR, or returns a lowercase string of $_ if EXPR is not specified.

$string = "HELLO";

$string = lc($ string);

print $string;

hex( hexadecimal)

Returns the value of the hexadecimal EXPR. $_ is assumed as EXPR if no other value is specified.

print hex(' ff'), "\ t", hex(' ee'), "\ t", hex(' ee');

chr( number)

Returns the character represented by N, or the value in $_ if N is not used.

print chr( 97); # Prints "a"

chop(value)

If used with a scalar value, removes the last character and returns the new string. When used in list context, removes the last character of all elements. The value of $_ is assumed if nothing else is specified.

$str = "Hello";

chop($ str);

print $str; # Prints "Hello"

chomp( value)

Same as chop, with one important exception. It removes the last character only if it is the same value as in $/, which in Windows is the new line character.

The Array

When putting a group of related scalar variables in one place, the array is the data structure that you will use in Perl. Its identifier type is the at sign (@), and as a place-holder the array contains ordinary scalar variables that are called elements because of the array context. The data structure is fully dynamic, so it will expand and contract as new elements are added or removed from the list, and there are several built-in functions for its management.

As elements are placed in the array, they are in an ordered list that when illustrated looks like a stack (Figure 2.1). The last element is always put on top of the stack; thus added items are placed there, too. However, this would be of little use if it were the only way of manipulating the array. Elements can be put anywhere in the array, although stack operations provides a natural flow of operations. First, however, to access the elements, you need to know that the list's index and first element start at 0. So if there are three elements, as in the preceding example, then the last element is accessed with 2. There are two more ways of accessing the last element of the array; the preferred way is by using the index -1. However, a cryptic-looking $# arrayname can be used as the element index when accessing the last element in the list.

In the array, the scalar variables are often related in some sense. For example, the array French_ Cities could contain all cities in France, and Ford_ Models could contain all models of the Ford car that are available. The array can be declared either as empty or with elements. In an ordinary array elements are enclosed within parentheses.

my @array = (); # Empty Array

my @secondarray = (" John", "Doe", 12); # Array with three elements

print $array[ 0], "\ n", $array[ 1], "\ n"; # Print element no 1 and 2

print $array[-1], "\ t", $array[$# array]; # Print the last element

When you want to save yourself some time, the qw function provides generalized quotes as you enter the elements into the array. It allows you to omit both quotation marks and comma signs. And on top of the qw function, there are a number of other built-in functions that relate to the array directly.

Related Functions

pop(@ array)

Removes and returns the last element of @array, and always uses the special variable @_ in subroutines and in every other case in which @array is not specified.

my @a = qw( John Doe 12); # Three-element array

$Age = pop(@ array); # Pop the last element

push(@ array, list)

Appends the elements of list to @array, and returns the new number of elements in the @array.

my @a = qw( John Doe 12); # Three element array "a"

my @b = qw( 1 2 3 4 5); # Five element array "b"

my $NumElements = push(@ a, @b); # Push "b" onto "a"

shift(@ array)

Removes and returns the first element of ARRAY. Uses @_ in subroutines if ARRAY is not specified.

my @a = qw( John Doe 12); # Three element array

my $FirstName = shift @a; # Remove the first element

unshift(@ array, list)

Appends a list of elements to the beginning of an existing array, then returns the number of new elements.

my @a = qw( John Doe 12); # Three element array

my @b = qw( 1 2 3 4 5); # Five element array

unshift(@ a, @b); # Unishift "b" in front of "a"

splice(@ array, offset [, length] [, list])

my @thislist = qw( 1 2 3 4 5); # Five element array

my @replace = qw( a b c); # Three element array

# Return and replace three elements

#

my @thatlist = splice(@ thislist, 0, 3, @replace);

# Print both arrays

#

print @thatlist, "\ n", @thislist;

reverse( list)

When LIST are scalars in list context, reverses their order. When the returned value is forced to a scalar, it comes back reverted.

@order = qw( 1 2 3 4 5 6 7 8 9 10); # The array to revert

$String = "Perl"; # The string to revert

@order = reverse @order; # Reverse the array

print @order; # Print the array

# The following forces reverse $string to be evaluated in

# scalar context -contrary to list-context

#

print scalar( reverse($ string));

map (EXPR, LIST)

map {BLOCK}, LIST

Map evaluates either the block or the expression it specifies for each element in the list used with it. Then it returns the list of the values that match the result.

The following example uses a block when mapping, and this is the first time the special variable $_ is introduced in this book. Essentially, in most list operations the value of each element in the list is assumed in the funny-looking $_ variable. This example multiplies the value of the array by itself.

my @list = qw( 1 2 3 4 5)

my @newlist = map { $_ * $_ } @list

print @newlist;

sort([ SUBNAME\ BLOCK], list)

sort( list)

It is pretty common to want to sort an array. Here are a few examples of numeric sorting:

@numbers = qw( 45 3 4 56 5 2 34 5);

# Sort numerically min to max

#

@listA = sort{$ a <=> $b} @numbers;

# Sort numerically max to min

#

@listB = sort{$ b <=> $a} @numbers;

And the same thing, but with characters:

@names = qw(" Bob", "Ron", "John", "Seb");

# Sort numerically min to max

#

@listA = sort{$ a cmp $b} @names;

# Sort numerically max to min

#

@listB = sort{$ b cmp $a} @names;

The first method does this by default, which you can see if you do the following:

print sort @names;

split(/ PATTERN/, EXPR [, LIMIT])

A regularly used function. Returns a list of every value in EXPR that was separated by PATTERN, or the original EXPR if no separation was made. LIMIT can restrict the number of scalars to return. If no parameters are specified, it will split $_ by white space.

The following will split a string by the comma character, which is escaped by a back-slash-- just in case-- and the result is that each word is returned into an array:

$String = "Joe, Blow, Hwy 24 S, Degas, Las Vegas";

@a = split(/\,/, $String);

join( EXPR, LIST)

This one does the opposite of what the previous function did:

@list = ('Joe Blow', 'Hwy 24 S, 'Degas', 'Las Vegas');

$String = join(",", @list);

The Associative Array

The associative array-- also known as the hash-- is an array, but it indexes its elements in a different manner. The type identifier is the percent sign (%), and the index is by key instead of integer. The hash table keys are strings that are associated with each value. The hash also expands and contracts dynamically.

my %hash = ('ColorA' => 'Blue',

'ColorB' => 'Red',

'ColorC' => 'Green');

And, indexed by key and accessed as a scalar variable.

print $hash{ 'ColorC'};

Related Functions

delete( key)

The delete function deletes a key and its value from the hash. It returns the value of the key or under if there is no such key.

delete($ hash{ key});

each( hash)

Returns the key and value of the next element in the hash.

my ($ key, $value) = each %Hash;

exists( key)

Returns true if the key exists in the given hash.

print exists($ hash{$ key});

keys( hash)

Returns a list of all the keys in the hash or the number of keys if evaluated in a scalar context. Can also be used to preallocate the number of keys in the hash instead of letting this be done dynamically.

print keys(% HASH), "\ n", scalar( keys(% HASH));

values( hash)

Returns a list of all the values in the hash or the number of values if evaluated in a scalar context.

print keys(% HASH), "\ n", scalar( keys(% HASH))

References and Nested Data Structures

A reference does not classify exactly as a variable. However, as just seen, the variables that have been presented only hold scalar values, and lack the ability to hold arrays and hashes. The reference solves that issue.

A reference points to an existing variable rather than representing its value. It knows how to locate the variable, but it does not hold the variable's value. In order to retrieve the value of the variable that the reference points to, it must be dereferenced. A reference that is dereferenced returns the actual variable so that its value can be directly accessed.

The most common way to create a reference is to use the backslash operator. This entails preceding any other variable, subroutine, or value with the backslash, such as:

# Makes a reference to a scalar variable

#

$reference1 = \$ someScalar;

# Makes a reference to array

#

$reference2 = \@ someArray;

The dereferencing of these is done as follows:

print $$ reference1;

print @$ reference2;

Placing the variable type being pointed to in front of the reference variable dereferences a reference. A reference can also point to another reference, and in that case, every reference that it points to must be dereferenced in its logical order. For example:

# A regular scalar

#

$scalar = "Hello World";

# Reference it in six steps

#

$refToScalar = \\\\\\$ scalar;

# This will print the location to its next reference and not "Hello

# World"

#

print $$ refToScalar, "\ n";

# This, however, will print "Hello World" since it is dereferenced

# in six steps. Not one, five or seven..

#

print $$$$$$$ refToScalar, "\ n";

It is very common to make the dereferencing more readable-- or quite possibly the opposite-- by enclosing the reference within curly braces:

# The array

#

@someArray = qw( 1 2 3 4 5);

# The hash

#

%someHash = ('a' => 'Anderson', 'b' => 'Bob');

# Reference the array

#

$reference1 = \@ someArray;

# Reference the hash

#

$reference2 = \% someHash;

# Dereference the array

#

print @{$ reference1};

# Dereference the hash

#

print %{$ reference2};

This would yield the expected and unwanted result of printing out all the elements within both list context variables. Why is it the expected behavior? First, a single element in a list is a scalar and must be accessed by a scalar, which means that neither @ nor % are valid for accessing single elements--$ must be used. Next, there is no index for the array or key for the hash to specify which element to retrieve. The following syntax is a clean way of accessing a scalar through the reference:

# Access the first element in the referenced array

#

print $reference1->[ 0];

# Access the value for key "a" in the referenced hash

#

print $reference2->{' a'};

This code is equivalent to the following dereferencing, which is commonly used when accessing list values in an object:

# Same as in previous example

#

print ${$ reference1}[ 0];

# Same as in previous example

#

print ${$ reference2}{' a'};

In either system of dereferencing, the syntax is descriptive in its own way. The former is a bit more explicit than the clean use of arrow notation. The final note about the basics of references involves a function and an alternative but ordinary way of creating references.

Whether you know that you need to verify that a variable is a reference or find out what type of data it is referencing, the built-in ref() function will return a value if the variable is a reference and false (a null value) if it is not a reference. Its true value will be a string of text that describes the type of data the reference is pointing to. In addition to this feature, a reference can point to an anonymous storage, which is a set of values not associated with a variable. For anonymous arrays, square brackets are used to enclose the elements instead of parentheses. For hashes, curly braces to show anonymous storage replace the parentheses.

# An anonymous array -notice the brackets because they symbolize it

# is anonymous and the $-prefix for someArray to show the reference

#

$someArray = [1, 2, 3, 4, 5];

# An anonymous hash -notice curly braces and $-prefix for someHash

#

$someHash = {'a' => 'Anderson',

'b' => 'Bob'};

# The following will print ARRAY

#

print ref($ someArray), "\ n";

# The following will print HASH

#

print ref($ someHash), "\ n";

# Print the first element

#

print $someArray->[ 0], "\ n";

# Print the 'a' key's value

#

print $someHash->{ 'a'};

With all of this discussion about references, let's look at how to create some complex data structures. The first one is an anonymous array that will contain arrays-- a list of lists.

# Create the reference to the anonymous array

#

$anonArray = [Text, [1,2,3]];

# This prints "Text"

#

print $anonArray->[ 0];

# This prints 2

#

print $anonArray->[ 1][ 1];

This declaration will produce the same output as the following one:

$MyText = "Text"

@MyNumbers = (1,2,3);

@references = (\$ MyText, \@ MyNumbers);

# Is equivalent to

# @references = \($ MyText, @MyNumbers);

A further example:

# Reference to anonymous array

#

$a = [" Text", [1,2,3], {" Hello"=>" World"}];

# Prints "World"

#

print $a->[ 2]->{ 'Hello'};

As seen, the references can hold many different values and are useful when building nested data structures. This can be elaborated on further. To read more about it, the following resources are recommended:

  • n See "Perl Referenced and Nested Data Structures" by Larry Wall et al. It is in the core Perl documentation, and it is a long and complete tutorial on references. Read it by issuing perldoc perlref from the command prompt.
  • See "Mark's Very Short Tutorial about References" by Mark-Jason Dominus. It was originally written for and published in The Perl Journal 3, #2, but has with permission been reprinted in the core Perl documentation. The document is a tutorial on references that, as the title says, is shorter than perlref, but delivers according to its introductory paragraph the 10 percent of perlref that is needed for 90 percent of the benefit. Run it from the command prompt by issuing perldoc perlreftut.
  • See "Manipulating Lists of Lists in Perl" by Tom Christiansen. It is in the core Perl documentation as the perllol page, and it describes everything known about arrays of arrays. It can be viewed by issuing perldoc perllol.
  • See "Perl Data Structures Cookbook" by Tom Christiansen. This document is a part of the core documentation, and can be read by issuing perldoc perldst.

File Handles

A file handle is an input/ output (I/ O) channel between your program and the operating system. In the operating system, there are three file handles already open for the program: STDIN (standard input), STDOUT (standard output), STDERR (standard error). But Perl is far from limited to these file handles as the only channels. You can open your own file handles to files on the system or use them for sending and receiving data from remote servers.

By default, the print and write functions will write to STDOUT, STDIN will wait for input to the program from the client, and STDERR is where an error message is channeled before being put into the special variable $!, which contains error messages. If you want a file handle that is not routed to either of the default channels, such as an I/ O connection to a file, you will need to open it explicitly by using the open( ) function.

open( FILE, "C:\\ file. txt");

This creates the file handle FILE, which can coexist with any other variables of the same name. The specified file is opened for reading only, and it will be read one line at a time or placed into an array by using the < > operator. Always close an open file handle when you don't need it any longer. For example:

open( FILE, "c:\\ file. txt");

@fileContents = <FILE>;

close( FILE);

When opening a file handle, there are four different modes that can be used, as seen in Table 2.6.

When you want to send data through the channel, you use the print function. For example, to append a line to a file, the following is correct:

open( FILE, ">> c:\\ file. txt");

print FILE "Append mode\ n";

close( FILE);

By default, any file opened by a file handle is opened as an ASCII (plain text) file. When the file you want to open is a binary file, you must specify that you are reading binary data with the command binmode (FILE); a binary file does not have lines in the sense ASCII files do.

  • See "Perlfaq 5" by Tom Christiansen and Nathan Torkington in the core Perl documentation. It contains information on files and formats, and among other practical things how to count the number of lines, delete a line, insert a line in the middle of a file, and read a file in by paragraphs, for example. Issue perldoc perlfaq5 from the command prompt.
  • See "Tutorial on Opening Things in Perl" by Tom Christiansen in the core Perl documentation. It has everything you need to know about binary files, file locking, and more.

Special Variables

In the Perl language, there are predefined variables that have special meaning to Perl. These variables are available to the programmer, and can be examined to obtain further information about what is going on or set some options for how Perl behaves in certain situations. For every special variable, there are one default name and one name that is defined when using the English module (Table 2.7).

The Control Structures of Perl

The control structures of a programming language are used to direct the flow of the program by determining when to execute a block of code or reexecute the same block, and at what point to stop executing a block of code. There are three types of control structures:

  • Conditional control statements
  • Loop control statement
  • Labels

Conditional Control Statements

The conditional control statement determines whether or not a block of code will be executed. It is either an if statement or an unless statement. The if statement will execute its associated block of code if the expression it poses is true.

if( Expression) {Block of code}

Should the expression not be true, the code within curly braces is safely ignored. Mathematical operators that can be used for conditional expression are shown in Table 2.9.

An if statement can, provided that its expression is false, be continued by further conditional control statements as elsif and else. The else statement will execute its block of code without testing an expression. It only requires that its preceding if has failed. The elsif, on the other hand, will test an expression if the control statement prior to it has failed.

my $name = 'Rena';

if($ name eq 'Bob') {

print "Your name is Bob!";

}

elsif($ name eq 'John') {

print "Your name is John!";

}

else {

print "Your name is $name!"

}

In contrast, the unless statement does prevent execution of the command on its left side provided that its expression is true.

my $number= 9;

print "$ number is less than or equal to five"

unless($ number>= 5);

The construct for the unless statement can be adapted by the if statement, too, in order to perform the operation to the left if the expression is true.

In addition to simple conditional expressions, a series of expressions can be stated by separating them with logical operators (Table 2.10).

if( LeftExpression && RightExpression) {

...

}

Loop Control Statements

A loop control statement is used to execute code a repeated number of times within the program.

The For Loop

The for loop has many different constructs, but one of the most common includes three steps:

  • An index value is initialized.
  • A conditional expression compares the index value to a maximum value to determine whether the block of code should be reexecuted or exited.
  • A mathematical expression defines how the index value is changed per loop to get close to the maximum value.

The most basic for loop initializes its index to 0 or 1 and increments the index by adding 1 to it per each loop for as long as the index is less than or equal to the maximum value.

for($ i= 1; $i <= 15; $i++) {

print "Loop $i", "\ n";

}

After having looped 15 times, it exits. A different kind of construct for the same loop is to use the range operator and numerically tell it how many times to loop the block of code.

for( 1.. 15) {

print "Loop $_", "\ n";

}

The Foreach Loop

The foreach loop is similar to the for loop but is used in list context. It takes an array as its only expression and assigns the current element in the array to a defined variable, loops the code, then moves to the next element in the array and repeats until there are no more elements.

my @friends = qw(' Mike', 'Rena', 'Andy');

foreach my $friend (@ friends) {

print "$ friend ", "\ n";

}

The While Loop

The while loop tests a conditional statement before it begins the loop. It is very often used in a context where you loop something until it reaches its end, such as a file or a result returned from a database query.

while($ i <= 15) {

print "Loop $i", "\ n"

$i++;

}

It can be used with mathematical expressions, as just shown. A more common use, however, is to open a file and print each line of the file until the end of the file is reached.

open( F, "somefile. txt");

while($ line = <F>) {

print $line;

}

close( F);

The Until Loop

The until loop is the complete contrast of the while loop. It executes the code it controls until its conditional statement is true. It is a very natural construct.

print $i++ until($ i== 10);

Labels

Labels mark up control structures, which makes it easier to refer to a block of code in detail. In the block context, next, last, and redo can be used to continue a block of code, exit by breaking out of it, or restart the loop.

GUESS: while( 1)

{

print "Concentrate on a number between 0 and 10: ";

$input = <STDIN>;

$a = int rand( 0,11);

print "The number is $a\ n";

next GUESS if ($ input!=$ a);

last GUESS if ($ input==$ a);

}

print "Great!";

The next, last, and redo functions can also be applied in a block of code that is not labeled. In such loops the function will apply to the innermost enclosing loop.

Regular Expressions

Regular expressions provide text matching and text manipulation capabilities. Perl has a set of the most powerful regular expressions available, and this is enough material to fill a book in itself.

Beginning Regular Expressions

Regular expressions can be made very simple or immensely complicated. First, Perl has pattern binding operators that indicate whether a regular expression should return success when it matches a pattern or when a pattern is not found. These operators are =~ and !~. The expression follows.

$text =~ operator/ pattern/ modifier

The operator indicates the type of operation-- matching, substitution, or translation-- to perform on the pattern.

Pattern Matching

The matching operator m is the default operator and is used to search for patterns in a string of text. In the expression, the pattern represents the text to match.

$text =~ m/ Hello/; # Match "Hello" in $text

You can omit the m operator since Perl defaults to using the pattern matching operator.

Modifiers

A modifier (Table 2.11) is used to tell the regular expressions how to treat the text used for matching and the pattern it matches.

$text = "hello world";

print $text= ~m/( HELLO)/ i;

Metacharacters

When expanding the regular expressions, certain characters with special meanings are used to steer the matching in the right direction. These characters, called metacharacters, are displayed in Table 2.12.

You can match an expression either at the beginning or the end of a string by using the ^ and $ metacharacters.

$text =~ /^ Hello/; # Match "Hello" at the beginning of $text

$text =~ /Hello$/; # Match "Hello" at the end of $text

Several expressions can be matched by enclosing each expression within parentheses; this will result in their matches being loaded into the special variables $n where n is a number for the match in the order it occurred.

$text = "Hello From Perl";

print $1, $2 if $text= ~/( Hello) From (Perl)/; # $1=" Hello",

$2=" Perl"

A minus sign can be used to indicate a group of letters from beginning to end on which the operation should occur (Table 2.13).

Pattern Quantifiers

The pattern quantifier (Table 2.14) simplifies the task of matching a certain pattern a number of times.

Predefined Character Classes

There are a number of predefined character classes with their own codes that can be used in regular expressions (Table 2.15).

Matching Locations in a String

Anchors are used in regular expressions to match at certain locations within a string. You have already seen ^ and $. Table 2.16 shows other anchors.

Extended Regular Expressions

Perl enables extended regular expressions to be embedded. Extensions are identified by a string enclosed within parentheses that begins with a question mark and then a function character (Table 2.17).

Substitution

The operator for substitution is used when matching and substituting a pattern. The pattern specifies what to look for, and then the replacement pattern tells what to replace it with.

# Does a case-insensitive match for January and replaces the first

# occurrence of January with February

#

$text =~ s/ january/ February/ i;

# Removes all HTML-tags in a string

#

$text =~ s/<.*?>// g;

# Substitutes a name in the form Firstname Lastname to Lastname,

# Firstname

#

$text =~ s/(\ w+)\ s(\ w+)/$ 2, $1/ g;

When the substitution is completed, the operator returns the number of substitutions made, including zero if none were made.

Translation

The translation operator is used to translate characters one by one. No modifiers are necessary due to the fact that characters are translated individually. For example:

# Convert all lower-case characters into uppercase

#

$text= ~tr/[ a-z]/[ A-Z]/;

Modular Perl Programming

To some degree, modular programming applies to most every written application and modern programming language today. First, what modular programming promotes is essentially a simple way of structuring a program by dividing its working parts into modules. Then, each module performs its own task, and as long as it only returns the projected result and works with the application, the module is doing its job to the fullest. Some examples of modules in an application are ones that print text, calculate sums, read the contents of a file, or put an interface for drawing graphics in the hands of the programmer. On its lowest level, when modularizing you hide away some data in a module and keep it protected until you call it from the program because you need it to perform its operation. And if you need to redo the operation, you can always call it again later in the program instead of it being lost forever. Also, modular programming expands its scope because code that was written to perform a task in one application should be reused in another application if it has the same needs, and therefore the modules become little packages of services. On its many levels, modular programming has been applied in forms such as subroutines in programs, packages in Perl, and object-oriented programming. Even programming models such as the Component Object Model encourage everything, including the parts of an operating system, to be completely modular.

Packages

A package is the foundation for modular programming in Perl, and it designates a new name space where the names of the parts of your program, such as variables, are located. It is an easy way to hide data away, and when something is declared outside of a package, it is put into the main name space, which is where all scripts in the book so far have resided-- although this is not explicitly declared. The following shows how to place a variable in a package and in the main package:

package myPackage;

$var = "Hello World";

1;

package main;

$var = "Main Package";

print $main:: var;

print $myPackage:: v ar;

1;

You could have skipped the main declaration and still have accessed your main variable as a part of that package. As just seen, when accessing something that belongs to an outside package, there are two colons separating the package name and the variable name.

Subroutines

A car is not just one big welded chunk of metal. When something breaks on the car, you get a new part to replace the old one. It is natural, practical, and clever to build a car from parts instead of making it as one single thing. Programming methodology is the same. You would not want to make everything into one big welded chunk because it is not natural, practical, or clever. Just as parts of a car can be improved and replaced, parts of code must undergo this process too. This is where modular programming comes into the picture. An application is a set of operations being performed, sometimes once and sometimes repeatedly, and it can often be divided into parts. From the beginning to the end of the program, you pick out every group of commands that perform an operation and modularize them by placing them into a subroutine. Next, the subroutine is given a name that describes its function.

sub NameOfSub

{

#... Some code to be executed...

A program can result in four subroutines. For example, sub A logs you onto your mail account, sub B receives e-mail, sub C sends e-mail, and sub D disconnects you from the mail server. The logical order of operation is to first execute sub A, then sub B, sub C, and sub D. In modular programming, you add a subroutine that acts as a controlling subroutine, whose only function is calling the other subroutines of the program.

sub ControlSub

{

A();

B();

C();

D();

}

sub A

{

# Logs onto mail account

}

sub B

{

# Receives mail

}

sub C

{

# Sends mail

}

sub D

{

# Disconnects from mailserver

}

Parameters

It would be difficult to send mail, for example, if no e-mail text or address to send to were passed to sub C. For this purpose there are parameters. The parameters are passed to a subroutine inside the parentheses that follow the name of the subroutine.

When programming Perl, it is at first difficult to get used to the rule that all parameters to a subroutine are automatically placed in the special variable @_ and therefore they must be either read or extracted from this special variable.

Calling the sub printString with a value as parameter

PrintString(" Hello From Perl!");

PrintString: Prints the parameter passed to it to

demonstrate a simple parameter

sub PrintString

{

my ($ param) = shift;

print $param;

}

The subroutine PrintString essentially encapsulates a call to a print function by which it prints out the value of the parameter sent. The former example simply outputs "Hello From Perl!" as a string. Admittedly, it is not a very useful thing to encapsulate as a subroutine, and especially not when all the functionality for printing a string is already in the print() function. It will probably create more of a headache than a function. Instead, a subroutine that can perform a calculation would be far more efficient than one that prints a simple statement to the standard output. So let's make the subroutine CalcAvg and pass a couple of numbers to it.

Call CalcAvg with the numbers to calculate average

CalcAvg( 1,5,6);

CalcAvg( 431,25,236,12,23,3);

CalcAvg: Read the parameters-array into one where the

numbers are stored. Extract the number of elements into $elements and set the total sum of their values to zero. Then loop each element of the array, add up the total, and divide it by the number of elements to get the average.

sub CalcAvg

{

my (@ numbers) = @_;

my ($ elements) = scalar(@ numbers);

my ($ total) = 0;

foreach my $number (@ numbers) {

$total+=$ number;

}

my $avg = ($ total/$ elements);

print "The average is: $avg", "\ n";

}

Performing calculations such as this is a much more useful task for a subroutine. It now encloses a group of commands that perform a joint operation and produce an expected result. Moreover, the routine can be reused in other applications. If you want to pass several arrays or hash tables to a subroutine, it is not possible the ordinary way. The reason is because the problem arises when you make a script as follows and attempt to read the parameters:

Pass one hash, array, and scalar to the subroutine

GetParams

my %param1 = ('a'=> 'Hello',

'b'=> 'World');

my @param2 = (1,2,3,4,5,6,7,8,9,10);

my $param3 = "Good morning";

GetParams(% param1, @param2, $param3);

GetParams: Shows how to fail getting the right values because the parameters were not passed by reference

sub GetParams

{

my (% param1, @param2, $param3) = @_;

print %param1, "\ n";

print @param2, "\ n";

print $param3, "\ n";

}

First, %param1 will have all variables passed to the subroutine loaded into it, including every single element of the arrays plus the scalar. And it is also the only value that will print, so in the end it produces a corrupted result. The result is to use references that are passed as scalars and extracted as scalars, but on the inside point to the original data structure they represent. Now the script can be rewritten.

Pass one hash, array, and scalar by reference to the

subroutine GetParams

my %param1 = ('a'=> 'Hello',

'b'=> 'World');

my @param2 = (1,2,3,4,5,6,7,8,9,10);

my $param3 = "Wednesday";

GetParams(\% param1, \@ param2, \$ param3);

GetParams: Receives a hash, array, and scalar that are passed by reference. Outputs them all.

sub GetParams

{

my ($ param1, $param2, $param3) = @_;

print %$ param1, "\ n";

print @$ param2, "\ n";

print $$ param3, "\ n";

}

Return Values

Whether an array, hash table, or single scalar is returned from a subroutine, there is only one way to return a value but two ways to write it. An expression can stand by itself at the end of the subroutine and it will return its value or result or the subroutine can be explicitly ended by the return function followed by the value to return.

retVal_ One: Returns the value of $c

sub retVal_ One

{

my ($ a, $b) = @_;

my $c = ($ a*$ b);

return $c;

}

retVal_ Two: Returns the value of expression $a*$ b

sub retVal_ Two

{

my ($ a, $b) = @_;

($ a*$ b);

}

In both cases, it is simply a matter of personal taste which one you like the best. In Perl, code can be written with very few lines. Returning two arrays from a subroutine can be a little trickier. It requires the use of references, again:

my ($ a, $b) = RetArrays();

print @{$ a}, "\ n\ n\ n", @{$ b};

sub RetArrays

{

my @arrayOne = qw( a b c);

my @arrayTwo = qw( d e f);

return(\@ arrayOne, \@ arrayTwo);

}

Prototypes

Prototypes allow you to specify the types of variables that are sent in the parameter list to the subroutine (Table 2.18).

Certain control characters can be applied to the prototypes as well. Putting a back-slash before one of the symbols will force a parameter to be of that exact type. A semi-colon is used to include optional parameters in the parameter prototypes to the right of the semicolon.

Further Reference

See "Perl Subroutines" in the core Perl documentation, which provides a thorough description on most topics related to subroutines, such as scope and subroutines, persistent private variables, prototypes, pass by reference, and much more. Read it from the command prompt by entering perldoc perlsub.

The Symbol Table

For every package, Perl keeps an internal hash table that is known as the symbol table. It points to named data in the package, such as variables, but since a hash table cannot accept duplicate names, the variables $myvar, @myvar, and %myvar cannot coexist. The solution is to point to these variables by name instead of identifier. What holds this name between the symbol table and the actual data is called a typeglob.

The Typeglob

The typeglob an internal data type that holds a symbol table entry. Identified and accessed by script with the *name syntax, the typeglob is what the symbol table uses when accessing a variable.

$name = "Bob";

@name = (" Bob", "Mary", "Joe");

%name = (" 2000" => 1_ 234_ 243);

*newName = *name;

print $newName, "\ n";

print @newName, "\ n";

print %newName, "\ n";

One caveat exists, though. Lexical variables are not listed in the symbol table, so they cannot be accessed by typeglobbing, and that is something to keep in mind. It has its areas of usage, though, such as when passing a file handle to a subroutine.

Example of opening a filehandle and passing it as a parameter to a filehandle, then trying to print the contents of it after the subroutine has manipulated the file -in this case, the subroutine reads a part from the filehandle, and then the calling point does the same after the subroutine has finished

open( FILE, "D:\\ c. pl");

GetParams( FILE);

print while(< FILE>);

GetParamFile: Localizes a filehandle, reads 50 characters and then prints the contents to the screen between delimiters that show that it was output within the subroutine

sub GetParamFile

{

local(* FILE) = @_;

print "-GetParamFile--\ n\ n".

read( FILE, $file, 50);

print $file;

print "-End GetParamFile--\ n\ n";

}

Modules

One level higher up than the subroutine, the module is separate from the program until imported. Modules are used because they already contain the code needed for an application or they extend the functionality of Perl. In its simplest form, a module is a package that is saved to a file with the same name as the package and the file extension .pm (Perl module). Not only is this one step further in modularizing code than what subroutines and packages do, it also handles the name space better than an ordinary package in terms of the junk it contributes.

The module is imported into a program by the use keyword followed by its name. For example, a module named StringThing is imported the following way:

use StringThing;

In the creation of a module, its name is normally nested so that it can be both descriptive and accurate for the task the module was written to perform. A name and then two colons before its module name normally precede the name of the module. The first name describes the type of functionality the module is specific for, or which group of modules it is fit for. For example, Windows-specific modules normally follow the convention Win32:: Modulename, while a module that handles some functionality related to images would be called Image:: Modulename. This is a nested module name, and although no such module as Image may exist, it is common to describe the functionality of modules so that both modules and the files they are packed into can be neatly organized and structured, not only in Perl.

Further Reference

  • See "Perl Modules" in the core Perl documentation for a description of how Perl modules work. Read it from the command prompt by entering perldoc perlmod.
  • See "Constructing New Perl Modules and Finding Existing Ones" in the core Perl documentation for exactly what the title says. Read it from the command prompt by entering perldoc perlmodlib.

Object-Oriented Perl

With Perl 5, the support for an object-oriented model of programming (OOP) was introduced. OOP is essentially a direct structure of programming for protecting and giving access to items such as variables and subroutines through a simple interface.

In OOP, the class is at the base level and contains a set of related variables and subroutines. The class belongs to the literal source code; thus the author decides the freedom or limitation of the contents that a class provides the programmer. In Perl, a class is simply a package, and the contents that belong to the package are known as methods and attributes instead of subroutines and variables. However, before data in a class can be accessed, an instance of the class must be created, and that instance is what is called an object.

In object-oriented programming, the class is the underlying source of the attributes and methods that can be accessed through the objects. In Perl, a class is simply a package that understands how to return objects. At least one of the subroutines in the class returns an object as a blessed reference. The blessing tells the object what package it belongs to, or gives it a sense of identity, so when a method is called through an object, Perl looks in the class the object refers to for the method to run.

After a class is constructed, it needs to be supplied with the method that returns the blessed reference as the class instance. In OOP terms, the method that fits the bill is called a constructor, and not only does it return the object, it is also a natural place to initialize any attributes with their values. In the constructor, normally the attributes are stored within an associative array because it provides a natural interface for the programmer. However, other data types such as an ordinary array are allowed, and what the blessed reference really cares about and returns is a reference of the decided-upon data type, but with a sense of identify. An object is freed from memory when the last reference to an object no longer exists, and although some languages require a destructor (as opposed to constructor) for this task, Perl automates it (although Perl gives the option of using explicit destructors).

package Computer;

sub new

{

my $package = shift;

my ($ processor, $mhz, $ram) = @_;

my $class = ref($ package) || $package;

my $self = {

"Processor" => $processor,

"Mhz" => $mhz,

"RAM" => $ram

};

bless ($ self, $class);

return $self;

}

1;

$box1 = new Computer(" Intel", "666", "128");

$box2 = new Computer(" Intel", "266", "64");

print $box1->{ Processor}, "\ t";

print $box1->{ Mhz}, " Mhz","\ t";

print $box1->{ RAM}, " Mb RAM","\ n";

print $box2->{ Processor}, "\ t";

print $box2->{ Mhz}, " Mhz", "\ t";

print $box2->{ RAM}, " Mb RAM\ n";

The big thing about classes is that they can inherit. When you inherit a class, you embed new functionality by utilizing the existing functionality of the inherited class.

This is called software reuse, since the child class can both use existing methods and provide its own functionality built upon the parent class. When it is desired to have one class inherit from another, the class name must be put in a class array named @ISA. The @ISA contains names of the parent class for the child, and next we let the parent class do the blessing of the reference.

package Thing;

sub new

{

my $package = shift;

my ($ name, $born, $weight, $height, $color) = @_;

my $class = ref($ package) || $package;

my $self = {'Name' => $name,

'Born' => $born,

'Height' => $weight,

'Weight' => $height,

'Color' => $color

};

bless($ self, $class);

return $self;

}

1;

package Fruit;

@Fruit:: ISA = (Thing);

sub new

{

my $package = shift;

my $class = ref($ package) || $package;

my $self = new Thing(@_);

bless($ self, $class);

return $self;

}

sub set

{

my $self = shift;

my ($ property, $value) = @_;

$self->{$ property} = $value;

}

1;

package Human;

@Human:: ISA = (Thing);

sub new

{

my $package = shift;

my ($ name, $born, $height, $weight,

$race, $country, $city, $occupation) = @_;

my $self = new Thing($ name, $born, $height, $weight, $race);

$self->{ Country} = $country;

$self->{ City} = $city;

$self->{ Occupation} = $occupation;

return $self;

}

1;

my $apple = new Fruit( 'Apple', 'Fall 2001', '2', '5', 'Green');

my $human = new Human( 'D. Thorne', 'Jul 15, 1975',

'5,6', '180', 'Caucasian', 'France',

'Paris', 'Student');

print $human->{ Occupation};

print $apple->{ Color};

$apple-> set( 'Quantity', '350');

print $apple->{ Quantity};

Thing is a general-purpose description we apply to objects in the world. A thing always has certain characteristics that we use to describe it: for example, a name (or, in the worst case, we call it unknown), the birthdate of the thing (or the date it was discovered), and physical characteristics such as height, weight, and color. Many items can be elaborated on from being a thing, which makes this an excellent parent class. In the code examples, the child classes Fruit and Human inherit from Thing. The fruit can be an apple, orange, pear, plum, and so forth because all of the class properties apply to it, so we make the fruit Apple, which was "born" or harvested in fall 2001. Its height and weight are given, and so is its color-- which describes the apple as either red or green, by which we can guess what the apple tastes like. In addition, Perl has a special-purpose method for creating new properties or setting existing properties. The method is named Set. A human can be categorized as a "thing," too. We know there is a given name and a date of birth by which we determine age, horoscope, and so on. In physical terms there are height and weight, and for humans, color is generally used to describe racial origin. As a few extra properties for the human, we have added country, location, and occupation. By encapsulating certain code and data in a parent class, software applications can inherit the functionality of the parent class and easily expand upon it. For example, a graphics class with functions for drawing primitives such as single pixels and lines can be inherited by a 3-D graphics class that uses the basic methods in a more specified context. The same primitives class could be inherited to an architecture drawing program, a statistics program, or a computer game, if you wish-- although that would probably require some tweaking. In OOP, the units are to be reusable and protected, and only do the task they were programmed for to return the expected and projected result.

Summary

In this chapter we have looked at the basics of Perl. As a language, Perl has three data types: the scalar variable, the array of scalar variables, and the associative array of scalar variables. The scalar variable can contain both numerical and character data, and there are both a regular expression engine and many built-in functions and operators that apply to the manipulation of the values of scalar data. Not exactly a data type, the reference is a scalar that points to the memory address of a variable such as a scalar variable or an array. This allows complex data structures such as lists of lists to be constructed. The language supplies control structures to regulate the flow of a program written in Perl. A conditional control statement can be used to execute a block of code only when a specified condition is met, and a loop control statement will execute a block of code a given number of times. Blocks of code may also be labeled in order to make it easier to handle the program flow programmatically. As a language, Perl fully supports a classic model and an object-oriented model of programming. On the most basic foundation of modular programming, Perl provides subroutines that enable encapsulation and reuse of code. A subroutine can consist of passed data, such as a scalar variable, on which operations are to be performed. Such a scalar variable passed to a subroutine is formally called a parameter. To complete this circle of passing variables, the subroutine can return the manipulated data to the point of the program that called the subroutine. The one thing to notice about parameters, however, is that when an array is passed, it must be passed to the subroutine by a reference to the array or else the subroutine will not receive every element of the array. A group of commonly used subroutines can be placed in a package and easily reused by future programs by saving the package as a Perl module, which has the file extension .pm. In general, a Perl module either builds upon the functionality of Perl by writing Perl code that is reusable, or extends the functionality of Perl by creating a module in a different language such as C. A standard set of modules known as the standard Perl modules are included with the installation of Perl. Since Perl supports an object-oriented programming model, a module or a program can be written as such, whereas a class is created as a placeholder for a set of variables and subroutines, of which selected variables and selected subroutines are exposed as the functionality of the class. In OOP terminology, variables become known as properties, and subroutines become known as methods. These properties and methods are accessed through an object, which is a reference to a class and is in fact the only direct way to access the class. If you write a module, it can be tailored to be easily installed with Perl Package Manager (PPM) from ActiveState. Many popular modules are already installable through PPM, and the number is constantly increasing. The reason is simple. It used to be a rather tedious process to install modules, and several pages of documentation would deal with how to install a module. With PPM, however, installing a module became a very convenient and quick process. If you want to install a module that is not yet available through PPM, you can look in the Perl documentation for instructions. The Perl documentation comes with the installation of Perl, and it is a very large set of documents that deal with every aspect of Perl. It contains everything about the language, frequently asked questions, and everything about the standard Perl modules. It is a very good compilation of documents, and if you are having Perl problems early on, you are guaranteed to find some answers in those documents.

From here, we will move on to programming the Active Server Pages objects that work at the ground level of the Web server.

Further Reference

  • See "Tom's Object Oriented Tutorial for Perl" by Tom Christiansen. It is in the core Perl documentation, and it covers issues such as constructors, class data, inheritance, and alternate object representations. Read it from the command prompt by entering perldoc perltoot.
  • See "Perl Objects" in the core Perl documentation for a more in-depth paper on Perl objects, what they are, how they come into being, and how to write your own destructors. Read it from the command prompt by entering perldoc perlobj.
  • See "Bag'o Object Tricks" in the core Perl documentation for hints on how to use Perl's object-oriented features. Read it from the command prompt by entering perldoc perlbot.
  • See "How to Hide an Object Class in a Simple Variable" by Tom Christiansen, and the TIEHANDLE by Sven Verdoolaege and Doug MacEachern. Read it from the command prompt by entering perldoc perltie.
Read More Show Less

Customer Reviews

Average Rating 5
( 1 )
Rating Distribution

5 Star

(1)

4 Star

(0)

3 Star

(0)

2 Star

(0)

1 Star

(0)
Sort by: Showing 1 Customer Reviews
  • Anonymous

    Posted Wed May 24 00:00:00 EDT 2000

    A Must Have...

    This book was easy to understand and literally provided the jump start to e commerce that our business needed. Having little experience linking databases with the net, it provided a 'tutorial approach' with clear examples and sound advice. I highly recommend this book.

    Was this review helpful? Yes  No   Report this review
Sort by: Showing 1 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)