With the advent of the World Wide Web and Web browsers, the Internet gained tremendous popularity. This greatly increased the volume of requests users made for information from Web servers. It became evident that the degree of interactivity between the user and the server would be crucial. The power of the Web resides not only in serving content to users, but also in responding to requests from users and generating dynamic content. The framework for such communication already existed through CGI. Most of the information users send to servers is text, thus Perl was a logical choice for programming the server side of interactive Web-based applications. Perl possesses simple, yet powerful, text-processing capabilities and is arguably the most popular CGI scripting language. The Perl community, headed by Wall (who currently works for O’Reilly & Associates as a Perl developer and researcher), continuously works to evolve the language, keeping it competitive with newer server-side technologies, such as Microsoft’s Active Server Pages (see Chapter 25).
Figure 27.2 presents a simple Perl program that writes the text "Welcome to Perl!" to the screen. Because the program does not interact with the Common Gateway Interface, it is not a CGI script. Our initial examples are command-line programs that illus-trate fundamental Perl programming.
# Fig. 27.2: fig27_02.pl
# A first program in Perl.
print( "Welcome to Perl!\n" );
Welcome to Perl!
Fig. 27.2 Simple Perl program.
Lines 2–3 use the Perl comment character (#) to instruct the interpreter to ignore everything on the current line following the #. This syntax allows programmers to write descriptive comments inside their programs. The exception to this rule is the “shebang” construct (#!) on line 1. On Unix systems, this line indicates the path to the Perl interpreter (such as #!/usr/bin/perl). On other systems (e.g., Windows), the line may be ignored, or it may indicate to the server (e.g., Apache) that a Perl program follows the state-ment.
The comment (line 2) indicates that the filename of the program is fig27_02.pl. Perl program file names typically end with the .pl extension. The program can be exe-cuted by running the Perl interpreter from the command-line prompt (e.g., the DOS prompt in Windows).
In order to run the Perl script, Perl must first be installed on the system. Windows users should see the “ActiveState Perl Installation” document at www.deitel.com for instruc-tions on how to install ActivePerl. ActivePerl is the standard Perl implementation for Win-dows. For installation on other platforms visit www.perl.com.
To run fig27_02.pl, type at the command prompt
where perl is the interpreter and fig27_02.pl is the Perl script. Alternatively, you could type
perl -w fig27_02.pl
which instructs the Perl interpreter to output warnings to the screen if it finds potential bugs in your code.
On Windows systems, a Perl script may also be executed by double-clicking its pro-gram icon. The program window closes automatically once the script terminates, and any screen output is lost. For this reason, it is usually better to run a script from the DOS prompt.
Line 5 calls function print to write text to the screen. Note that because Perl is case-sensitive, writing Print or PRINT instead of print yields an error. The text "Welcome to Perl!\n" is surrounded in quotes and is called a string. The last portion of the string—the newline escape sequence, \n—moves the output cursor to the next line. The semicolon (;) at the end of line 5 terminates Perl statements. Lastly, notice that the argu-ment passed to function print (i.e., the string that we wish to print) is enclosed in paren-theses (). These parentheses are not required; however, we suggest that you use parentheses as often as possible in your programs, to maintain clarity. In this example, we use parentheses to indicate what we want printed. We will demonstrate the use of paren-theses throughout the chapter.
Perl has built-in data types (Fig. 27.3) that represent different kinds of data. Notice that each variable name has a specific character (i.e., $, @ or %) preceding it. For example, the $ character specifies that the variable contains a scalar value (i.e., strings, integer numbers, floating-point numbers and references). The script fig27_04.pl (Fig. 27.4) demon-strates the manipulation of scalar variables.
# Fig. 27.4: fig27_04.pl
# Program to illustrate the use of scalar variables.
$number = 5;
print( "The value of variable \$number is: $number\n\n" );
$number += 5;
print( "Variable \$number after adding 5 is: $number\n" );
$number *= 2;
print( "Variable \$number after multiplying by 2 is: " );
print( "$number\n\n\n" );
# using an uninitialized variable in the context of a string
print( "Using a variable before initializing: $variable\n\n" );
# using an uninitialized variable in a numeric context
$test = $undefined + 5;
print( "Adding uninitialized variable \$undefined " );
print( "to 5 yields: $test\n" );
# using strings in numeric contexts
$string = "A string value";
$number += $string;
print( "Adding a string to an integer yields: $number\n" );
$string2 = "15charactersand1";
$number2 = $number + $string2;
print( "Adding $number to string \"$string2\" yields: " );
print( "$string2\n" );
The value of variable $number is: 5
Variable $number after adding 5 is: 10
Variable $number after multiplying by 2 is: 20
Using a variable before initializing:
Adding uninitialized variable $undefined to 5 yields: 5 Adding a string to an integer yields: 20
Adding 20 to string "15charactersand1" yields: 15charactersand1
Fig. 27.4 Using scalar variables
In Perl, a variable is created the first time it is encountered by the interpreter. Line 5 creates a variable with name $number and sets its value to 5. Line 8 adds 5 to $number, which results in the value 10 being stored in $number. Notice that we use an assignment operator (+=) to yield an expression equivalent to $number = $number + 5, which adds 5 to the value of $number and stores the result in $number. Assignment operators (i.e., +=, -=, *= and /=) are syntactical shortcuts. Line 9 calls function print to write text fol-lowed by the value of $number. Note that the actual value of $number is printed, rather than "$number"; when a variable is encountered inside a double-quoted ("") string, Perl uses a process called interpolation to replace the variable with its associated data. On line 11, we use a shortcut similar to the one used on line 8: *=. In this case, we multiply $number by 2 and store the result in $number.
In Perl, uninitialized variables have the value undef, which evaluates to different values depending on the variable’s context. When undef is used in a numeric context (e.g., $undefined on line 19), it evaluates to 0. In contrast, when it is interpreted in a string context (such as $variable in line 16), undef evaluates to the empty string ("").
Lines 24–31 show the results of evaluating strings in numeric context. Unless a string begins with a digit, it is evaluated as undef in a numeric context. If it begins with a digit, every character up to, but not including, the first nondigit character is evaluated as a number, and the remaining characters are ignored. For example, the string "A string value" (line 24) does not begin with a digit and, therefore, evaluates to undef. Because undef evaluates to 0, variable $number’s value is unchanged. The string "15charactersand1" (line 28) begins with a digit and is interpolated as 15. The char-acter 1 on the end is ignored, because there are nondigit characters preceding it. Evaluating a string in numeric context does not actually change the value of the string. This rule is shown by line 31’s output, which prints the original string, "15charactersand1".
Notice that the programmer does not need to differentiate between numeric and string data types, because the interpreter’s evaluation of scalar variables depends on the context in which they are used.
Perl provides the capability to store data in arrays. Arrays are divided into elements, each containing a scalar value. The script fig27_05.pl (Fig. 27.5) demonstrates some techniques for array initialization and manipulation.
# Fig. 27.5: fig27_05.pl
# Program to demonstrate arrays in Perl.
@array = ( "Bill", "Bobby", "Sue", "Michelle" );
print( "The array contains: @array\n" );
print( "Printing array outside of quotes: ", @array, "\n\n" );
print( "Third element: $array[ 2 ]\n" );
$number = 3;
print( "Fourth element: $array[ $number ]\n\n" );
@array2 = ( 'A' .. 'Z' );
print( "The range operator is used to create a list of\n" );
print( "all capital letters from A to Z:\n" );
print( "@array2 \n\n" );
$array3[ 3 ] = "4th";
print( "Array with just one element initialized: @array3 \n\n" );
print( 'Printing literal using single quotes: ' );
print( '@array and \n', "\n" );
print( "Printing literal using backslashes: " );
print( "\@array and \\n\n" );
The array contains: Bill Bobby Sue Michelle
Printing array outside of quotes: BillBobbySueMichelle
Third element: Sue
Fourth element: Michelle
The range operator is used to create a list of all capital letters from A to Z:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Array with just one element initialized: 4th
Printing literal using single quotes: @array and \n
Printing literal using backslashes: @array and \n
Fig. 27.5 Using arrays
Line 5 initializes array @array to contain the strings "Bill", "Bobby", "Sue" and "Michelle". In Perl, all array variable names must be preceded by the @ symbol. Parentheses are necessary to group the strings in the array assignment; this group of ele-ments surrounded by parentheses is called a list. In assigning the list to @array, each person’s name is stored in an individual array element with a unique integer index value, starting at 0.
When printing an array inside double quotes (line 7), the array element values are printed with only one space separating them. The values are separated by whatever is in special variable $", which, by default, is a space. If this value were changed to the letter "a", all the array elements would be printed with the character "a" between them. If the array name is not enclosed in double quotes when it is printed (line 8), the interpreter prints the element values without inserting spaces between them.
Line 10 demonstrates how individual array elements are accessed using square brackets (). As mentioned previously, if we use the @ character followed by the array name, we reference the array as a whole. But if the name of the array is prefixed by the $ character and followed by an index number in square brackets (as in line 10), it refers instead to an individual element of the array, which is a scalar value. Line 13 demonstrates the use of a variable as the index number. The value of $number[ 3 ] is used to get the value of the fourth element of the array.
Line 15 initializes array @array2 to contain the capital letters A to Z inclusive. The range operator (..) specifies that all values between uppercase A and uppercase Z be placed in the array. The range operator can be used to create a consecutive series of values, such as 1 through 15 or a through z.
The Perl interpreter handles memory management. Therefore, it is not necessary to specify an array’s size. If a value is assigned to a position outside the range of the array or to an uninitialized array, the interpreter automatically extends the array range to include the new element. Elements that are added by the interpreter during an adjustment of the range are initialized to the undef value. Lines 20–21 assign a value to the fourth element in the uninitialized array @array3. The interpreter recognizes that memory has not been allo-cated for this array and creates new memory for the array. The interpreter then sets the value of the first three elements to undef and the value of the fourth element to the string "4th". When the array is printed, the first three undef values are treated as empty strings and printed with a space between each. This accounts for the three extra spaces in the output before the string "4th".
To print special characters, like \, @ and " and not have the interpreter treat them as an escape sequence or array, Perl provides two options. The first is to print (lines 23–24) the characters as a literal string (i.e., a string enclosed in single quotes). When strings are inside single quotes, the interpreter treats the string literally and does not attempt to inter-pret any escape sequence or variable substitution. The second choice is to use the backslash character (line 26–27) to escape special characters.
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.