# A Brief Introduction to Perl XML

Perl is a general-purpose scripting language ideally suited to handle words and text. Perl is admired for staying simple when you need to do simple things, but also having the power todo nearly every chore that a system administrator might require. To quote the Perl gurus: "It makes the easy things easy, and the difficult things possible."

Perl is a great language because after you get to know it, you can express yourself quickly and easily. Perl has a way of allowing you to do a lot by writing very little. It dispenses with a lot of programming "clutter" that accompanies many other programming languages. This ability allows you to write scripts in a natural and concise manner.

Another of Perl's strengths is that it offers many ways of accomplishing any particular bit of programming. This strength inspires Per programmers to quote the motto "TIMTOWTDI" (pronounced timtoady), which is the acronym for "There Is More Than One Way To Do It." This variety leads to different personal styles and preferences, as well as a great deal of fun, comfort, and joyful discovery as you learn the ins and outs of the language.

Writing a Simple Program in Perl

After you install Active Perl, you can try out the first Perl program.

Create the following file in the cgi-bin folder of your Apache installation.

Examine the program. This is similar to a typical "Hello World" program. It waits for user input and then displays a message.

Note?/td>Note that any line that starts with a # is a comment.

The first line with a # and a ! indicates the language used by this script, which is Perl. <STDIN> represents the standard input device, which is usually the keyboard.

Execute the file from the command line by using the following syntax:

perl try.pl

If you have installed the Active Perl package, then this program should execute without a problem.

In the preceding program, you stored the input from the keyboard into a variable. Variables in Perl should consist of the character $followed by at least one letter, which can be further followed by any number of letters, digits, or underscore characters. Operators in Perl In addition, similar to any other scripting language, Perl allows you to use most of the basic arithmetic operators. Here is a sample program that illustrates the use of variables and a basic multiplication operator: The input value stored in the variable,$KGrms, includes the number you entered and a new line character (from the Enter you pressed after the number). The chop function chops off the last character, which is a space.

Programming Constructs in Perl

Perl supports most of the programming constructs that other programming languages support. Let's look at some of the basic decision making and looping constructs. The If-Else statement is probably the most widely used decision-making statement. The following example shows the syntax of the If-Else statement::

Here are examples of the while loop and the for loop.

Another use for the for loop is working with an array, as shown here:

The preceding code will work through the array, assigning the values to the variable $cat. Receiving Keyboard Input The following code accepts keyboard input and displays the characters entered: The script accepts a line of input from the standard input device—usually the keyboard—stores it in a variable, and then displays the contents of the variable. Reading and Writing to Files To open a file on the local system, you will need to use the open library function. The syntax for the open function is as follows: open (var, filename); where: • var represents the name you want to use in your Perl program to refer to the file. A file-variable name can be any sequence of letters, digits, and underscores, as long as the first character is a letter. • filename represents the location of the file on your machine. You must decide how you want to open the file. Three different file access modes are available in Perl: • Read mode. Allows the script to read the contents of a file but not make modifications to it. • Write mode. Allows the script to overwrite the current contents of the file. • Append mode. Allows the script to retain the existing content and add new content to it, if required. You can use the following syntax to check whether a file has been opened successfully: After the file is open, you can read its contents and store them in a variable as shown next: Here is a short script that reads the contents of a file and displays it: Terminating a Program If an error occurs, you can use the die command to terminate the script with an error message, as shown in the following code: Matching a Pattern A pattern is a sequence of characters to be searched for in another string that is normally specified within two slashes (/pattern/). Consider the following syntax: In the preceding line of code, the =~ operator checks whether the pattern is within the string stored in the variable$line. The operator returns a non-zero value if a pattern is found, and 0 if the pattern is not found.

Some characters have special meanings as part of a pattern.

• The special character + means "one or more of the preceding characters." For example, the pattern /co+1/ matches col, column, cooler, cool, and so on.
• The [] special character enables you to define patterns that match one of a group of alternatives. For example, /p[ea]t/ matches pet or pat but not peat.
• The * special character matches zero or more occurrences of the preceding character. For example, /re*f/ matches ref and reef but not reaf.
• The ? character matches zero or one occurrence of the preceding character. For example, the pattern /spo?t/ matches spt and spot but not spoot.
• The backslash \ special character is used to include a special character as a normal character in a pattern. You need to precede the special character with a \ to treat it as a normal character. For example, to check for one or more occurrences of * in a string, use the pattern / \*+/.
• The pattern anchors ^ and $ensure that the pattern is matched only at the beginning or the end of a string. For example, the pattern / ^cla/ matches only if c, l, and a are the first three characters in the string. Similarly, the pattern /cla$/ matches only if these are the last three characters in the string. Following is a sample script that searches for a word in any number of sentences entered:

Subroutines

In Perl, a subroutine is a separate body of code designed to perform a particular task, much like a function of any programming language. Also similar to functions, you need to invoke the subroutine to execute it. This process is called a subroutine invocation.

Here is the code for a sample subroutine, which simply adds two numbers and returns the value:

Formatting the Output of a Script

To display output using a print format, you need to set the system variable \$~ to the format you want to use and call the built-in function write. Here is a code sample that illustrates this:

Caution?/td>Don't miss the period in the preceding line, which indicates the end of the format statement.

An Introduction to Packages

A package is a collection of subroutines. Perl has two types of packages: modules and classes. Modules are collections of simple subroutines, whereas classes are based on object-oriented features. Although you can invoke a subroutine of a module directly, you can invoke subroutines (or methods) of a class only by using instances or objects of the respective class. Classes can have special subroutines, which act as constructors and destructors.

We will next introduce you to the general syntax for creating a module. First, create a text file called Demo.pm.The .pm extension, which is the default extension for packages, stands for Perl module.

Note that all Perl packages end with a "1;". This statement is required for all packages in Perl. If you forget this statement, Perl won't process your package.

The CGI.pm Module

The CGI.pm module contains many functions that are helpful when you are writing CGI applications and have to output a lot of stuff in HTML. You can access this module as a set of functions or as objects. The following two code samples illustrate this.

The first code snippet accesses the module using the functional method:

The next code snippet invokes the module using objects:

This concludes a brief discussion of Perl. You now know the basics that are required to understand the examples given in the rest of the chapter.

Introduction to SOAP::Lite

To program Web services in any language, you need a SOAP tool that serializes and deserializes SOAP messages. For Perl, SOAP::Lite is the tool. In this section, you'll learn about the SOAP::Lite tool, created by Paul Kulchenko. As you use it, you'll find that this tool makes programming Web services in Perl quite easy.

Perl is one of the most popularly used scripting languages for creating CGI scripts. Therefore, the Web service design involves creating a CGI script to accept requests from a SOAP client and, in turn, pass on the request to a class, which will service the request.

Sample Web Service

You can create a simple Hello World service. The process involves creating three files:

• The CGI script
• The CGI class
• The client

Here is the CGI script and the class code. Note that you can install the class in a separate Perl module (.pm) file:

The preceding code consists of a CGI script that simply passes the HTTP calls, which it receives, to the class Class1.

Following is the Perl client that calls the SOAP service:

In the client code, the uri() refers to the class on the server, and the proxy() identifies the CGI script that provides access to the class. proxy(). proxy is the address of the server that is hosting the Web service. Each server can offer many different services through one proxy() URL. Each service has a unique URI-like identifier, which you specify to SOAP::Lite through the uri() method.

When you run your application, you should see the familiar Hello World message.

Debugging SOAP Scripts

If you need to debug a SOAP::Lite script, you have the option of viewing the client-server transactions in detail. The details displayed include how the request is processed, which is handy for tracking down errors. Most errors result from a mismatched URI or proxy address and are visible in the text of the SOAP packet. Add +trace => all after use SOAP: Lite to send all debugging output to the STDERR output stream:

SOAP Autodispatch

SOAP::Lite also has a feature called Autodispatch that allows you to bind remote methods to the execution of your program. When Autodispatch is enabled, methods that aren't available locally are automatically sent to a remote server for execution. Autodispatch using SOAP is a transparent process. In this process, after you establish the remote server, you can call the remote methods without referring to the remote server.

Because they aren't locally defined, the greet and RemoteMethod functions are sent automatically to the remote server named in proxy for execution. Using Autodispatch is like inheriting from another class; therefore, be sure to define a function with the same name as the one you're trying to call on the remote server.

Creating Clients for Web Services Using SOAP::Lite

SOAP::Lite is a great tool for creating client application for Web services. In this section, you will look at creating Web service clients for live services.

Here is the code for the client script.

Notice that theimplementation does not use the WSDL of the Web service to access the Web service.

Following is one more example that actually uses the WSDL of a Web service to access the Web service:

As you can see, SOAP::Lite does indeed simplify the task of creating Web service clients.