Perl in a nutshell…
Prof. Rasley
First CGI Script and Perl
– shebang line ‐ tells the operating system where the Perl interpreter is located ‐ necessary on UNIX
– comment line – ignored by the Perl interpreter – End statements with semicolon
– newline character – to end a line and create a new line
First CGI Script and Perl
• Content‐type header
– tells the script what type of output there will be – print “Content‐type: html/text\n\n”;
• print is used to output information within the quotation marks to the browser
• HTML tags are created dynamically using print statements
• When you run a program, be sure to change the permissions to 755 as with PHP
Creating a Link to a Script
• When creating a script, remember to:
– Enter the shebang line (required for UNIX) – Enter a comment that includes the name of the
script and the script’s purpose – Enter the Content‐type line:
• print “Content‐type: text/html\n\n”;
print Function
• Perl can generate HTML output in various ways:
– print – printf – “here” documents
• Syntax for print:
– print output;
• Output can be strings, functions, variables
• Output can be an expression or a list of expressions, separated by commas
Parsing Data
• To use CGI.pm, you need to include the statement:
– use CGI qw(:standard);
• qw = quote words
• Same as the statement ‐ use CGI(‘:standard’);
• :standard is an import tag
– Tells the Perl interpreter to allow the use of the standard features of the CGI.pm module
• Can find out more about CGI.pm, by typing:
– perldoc CGI.pm
Parsing Data
• The param function accesses the value associated with a key
– param is part of the standard features of CGI.pm – Syntax:
• param(key) where key is in single or double quotation marks
• Example:
– param(‘state’);
– param(“state”);
Parsing Data
• If the offline mode message does not appear, the use CGI statement needs to be changed:
– use CGI qw(:standard ‐debug);
– This is including the ‐debug pragma, and tells CGI.pm to pause to let you type in the data
• pragma = special type of Perl module.
Variables in Perl
• Variable
– Location in the computer’s internal memory where a script can temporarily store data
– Each variable has a data type
• Determines the kind of data the variable can store
• Perl has 3 data types:
– Scalarvariable – can store one value
» Example: number or string
– Arrayvariable – can store lists or sets of values – Hashvariable – can store lists or sets of values
– Each variable has a name
Variables in Perl
• Scalar variable naming:
– Must begin with dollar sign ($) – Followed by a letter
– Optionally followed by one or more letters, numbers, or underscores
– Valid names: $city, $inc_tax – Variable names are case‐sensitive:
• $city and $CITY are two different variables – Should use descriptive names
Variables in Perl
• Perl does not require variables to be explicitly declared – By default, variables are created “on the fly”
• Variable exists as soon as you use the variable
– It is a good programming practice to not allow variables to be created “on the fly”
• use strict;
– Prevents Perl from creating undeclared variables
• Syntax to declare variables:
– my (variablelist);
• Example:
– my ($hours, $gross, $sales);
Accessing the Values Received from an Online Form
• Data sent using an online form must also be parsed by the script
– Can use same parsing routing in CGI.pm
• param function
The Bonus Calculator Form
• The <FORM> tag uses 2 properties:
– ACTION
• The name of the CGI script that will process the form data
– METHOD
• Controls how your web browser sends the form data to the Web server
• GET
– Defaultmethod
– Appends form data to the end of the URL – Similar to sending data using a hyperlink
• POST
– Sends form data in a separate data stream – Safer than GET
» Some web servers limit the size of the URL
The Bonus Calculator Form
The Bonus Calculator Form
Array Variables
• Array declaration syntax:
– my arrayname=(list);
• Name of array must begin with at sign (@)
• After the @, the name must start with a letter, and then a combination of
– letters, numbers, or underscores
• The list consists of values separated by commas
Array Variables
• Array declaration examples:
– my @sales = (25000, 35000, 10000);
– my @cities = (“Boston”, “Chicago”, “Detriot”, “San Diego”);
Array Variables
• Accessing the array
– Replace the @ in the array name with: a $, array name, and index enclosed in square brackets ([ ])
– Example:
– my @sales = (25000, 35000, 10000);
• $sales[0]=25000
• $sales[1]=35000
• $sales[2]=10000
– A scalar variable within an array can be used the same
way as any other scalar variable
Using an Array
• This code now includes declaring the @models array, as well as accessing and printing the corresponding model name
Hash Variables
• Hash variable, or hash:
– Collection of related scalar variables – Like an array variable
– Instead of using an index number, a hash uses a key name
– Like an array’s index numbers, the keys are assigned to the scalar variables when the hash is created – Another name for a hash is an associative array
Hash Variables
• Hash declaration syntax:
– my hashname = (key1, value1, key2, value2,...keyn, valuen);
• Name of hash must start with percent sign (%)
• After %, the name must start with a letter, and then a combination of letters, numbers, or underscores – Can declare the hash in one line, or multiple lines
Hash Variables
• Hash declaration example #1:
– my %sales = (“Jan”, 25000,
“Feb”, 35000,
“Mar”, 10000);
– “Jan”, “Feb”, and “Mar” are keys
– Their corresponding values are 25000, 35000, 10000
Hash Variables
• Hash declaration example #2:
– my %cities = (“617”, “Boston”,
“312”, “Chicago”,
“313”, “Detroit”,
“619”, “San Diego”);
– Keys: “617”, “312”, “313”, “619”
– Values: “Boston”, “Chicago”, “Detroit”, “San Diego”
Hash Variables
• Accessing the hash:
– Replace the % in the hash name with a $, array name, key enclosed in braces ({ })
– Example:
– my %sales = (“Jan”, 25000,
“Feb”, 35000,
“Mar”, 10000);
• $sales{Jan} = 25000
• $sales{Feb} = 35000
• $sales{Mar} = 10000
Hash Variables
• Accessing the hash:
– If a key has a space:
• Use single or double quotation marks within the braces
• Example:
– $state {‘New Mexico’}
– $state {“New Mexico”}
– A scalar variable within a hash can be used the same as any other scalar variable
Using a Hash
• This code now includes declaring the %systems hash, and printing out the full operating system name by accessing the
%systems hash
The foreach and for Statements
• 3 basic structures (control or logic structures) make up scripts:
– Sequence
• Script statements are processed in the order they appear in the script
– Selection
• Make a decision or comparison, and then select one of 2 paths based on the result
– Repetition (loop)
• Repeat a block of instructions for a specified number of times or until a condition is met
• Examples: foreach, for, while, until
The foreach and for Statements
• foreach:
– The foreach statement repeats one or more instructions per element in a group, like an array – When each member of the array has been processed,
the loop stops – Syntax:
foreach element (group) {
One or more statements processed per element in group
}
The foreach and for Statements
• foreach Example:
my ($num, @numbers);
@numbers = (5000, 200, 100, 3);
foreach$num (@numbers) {
print “$num<BR>\n”;
}
Result:
5000 200 100 3
The foreach and for Statements
• for:
– The for statement is used to repeat one or more statements as long as the
loop conditionis true
– 3 arguments are used:
• initialization argument – counter variable
• loop condition
– Boolean expression that evaluates to true or false – Loop stops when loop condition evaluates to false
• update
– Updates the counter variable in the initialization argument
The foreach and for Statements
• for:
– Syntax:
for(initialization; loop condition; update) { one or more statements to be processed
as long as the loop condition is true }
– Example:
my $num;
for ($num = 1; $num < 4; $num = $num + 1) { print “$num<BR>\n”;
}
Result:
1 2 3
Updating the Juniper Printers script
• foreachwill be used to process each member of the @sysletter array
• open function examples:
• Location of files to create or open if no path is used:
– UNIX– same directory as script
– Windows– default directory, typically cgi‐bin
• It is good practice to begin filehandle names with IN or OUT, depending on the filehandle is used
Creating and Opening a File while and until statements
• while statement:
– Used to repeat a block of instructions while a condition is true – Syntax:
while (condition) {
statement(s) to process while condition is true }
– Example:
my ($x, @nums);
@nums = (5000, 200, 100, 3);
$x = 0;
while ($x < 4) { print “$nums[$x]\n”;
$x = $x + 1;
}
Result:
5000 200 100 3
• until statement:
– Used to repeat a block of instructions until a condition becomes true
– Syntax:
until (condition) {
statement(s) to process until condition is true }
– Example:
my ($x, @nums);
@nums = (5000, 200, 100, 3);
$x = 0;
until ($x == 4) { print “$nums[$x]\n”;
$x = $x + 1;
}
while and until statements
Result:
5000 200 100 3
Using the die function
• If the open function fails, by default, the script continues to run
• die function:
– Displays message and exits script if there is an error while accessing a file
– Syntax:
• die message
Using the die function
Writing Records to a File
• Can use print to write to the filehandle representing an open file
– print filehandle data\n;
• Typically, each record in a datafile is written to a separate line
Writing Records to a File
• If a record contains more than 1 field, then a field separator (delimiter) is used:
– Examples:
• comma (,)
• colon (:)
• ampersand (&)
• tab (\t)
• pipe (|)
– Field separator must not be part of the data in the fields
• Otherwise, when reading the data from the file, there will be problems confusing the separator in the data and the actual field separator
Closing a File
• To make sure that no data is lost, any opened files should be closed before the script ends
• Syntax:
– close (filehandle);
• A file is automatically closed when the script ends, but it is good practice to close the file when finished using it
Reading Records into an Array
• Syntax:
– arrayname = <filehandle>;
– Reads records from a file into an array – no matter how many records are in the file!
– <> = angle operator
– Angle operator instructs to read record from filehandle and store each in a scalar variable in arrayname
• Example:
– @records = <INFILE>;
More on foreach
• Can declare the loop variable in the foreach statement
– The variable can be used within the loop, and will be removed
from memory when the loop has completed running
Removing the Newline Character
• Chomp function can be used to remove the newline character (\n) from the end of a record
• Syntax:
– chomp (variable);
• Example:
– chomp ($rec);
Using the split function
• The split function can be used to divide a string of characters into separate parts based on a pattern
• Syntax:
– split (/pattern/, string);
• Example:
– split (/,/, “John,Jane”);
• Splits the string “John,Jane” into 2 parts – John and Jane
Using the split function
The sort function
• sort function:
– temporarily sorts a list of values – Syntax:
• sort (list);
– Can be used to sort a comma‐separated list of values, array, or keys of a hash
The keys and sort functions
• keys and sort can be used together, as in Example 3
– sort function will alphabetize the keys in a hash
Coding the Selection Structure in Perl
• if statement:
– Used for coding the selection structure – Syntax:
if (condition) {
one or more statements to be processed when the condition evaluates to true
} else {
one or more statements to be processed when the condition evaluates to false
}
Comparison Operators
• Comparison operators are also called relational operators
– One set to compare numeric values – One set to compare string values – Each operator has a precedence value
• The order in which Perl performs the comparisons in an expression
• For example, comparisons with a precedence number of 1 will be performed before comparisons with a precedence of 2
Comparison Operators for Numeric Values
• Test for equality using 2 equal signs ==
– Easy to confuse with the assignment operator (=)
Comparison Operators for Numeric Values Comparison Operators for String Values
• When comparing 2 strings, the ASCII value of each character in the first string is compared to the corresponding character in the second string
– Capital letters have a lower ASCII value than their corresponding lowercase letters
Comparison Operators for String
Values Logical Operators
• and and or are the most commonly used logical operators
– Combine multiple conditions into one compound condition – and:
• All conditions must be true for the compound condition to be true
• If the first condition is false, the second condition will not be evaluated
– or:
• Any condition must be true for the compound condition to be true
Validating Script Input Data
• Can choose to check for correct or incorrect values
Adding Items to an Array
• The push function is used to add item(s) to the end of an array
– Syntax:
• push (array, list);
– Examples:
• push (@states, “Hawaii”);
• push (@nums, 10, 25);
– Can also add items to the end of an array with an assignment statement
• Syntax:
– array = (array, list);
• Example:
– @nums = (@nums, 10, 25);
Determining the Size of an Array
• There are 2 ways to determine the size of an array:
– Assign the name of an array to a scalar variable
• Example:
– $size = @errors;
– Now, $size will be equal to the number of scalar variables in the array
– The
scalar function• Syntax:
– scalar (array);
• Example:
– print scalar (@errors);
– Will print the number of scalar variables in the @errors array
Using the if/elsif/else Form of the if statement
• if/elsif/else structure can be used if there are multiple alternatives
– Can choose to use nested if statement(s) or use elsif for every alternative
Using if/elsif/else Functions
• Function (or subroutine)
– Block of code that begins with keyword sub – Code for a function can be in the same script or
can be in a separate file
• Examples:
– Code for param is stored in CGI.pmfile – Code for push is stored in perl/perl.exe
Functions
• Code for a function is processed when the function is called or invoked
– Invoke a function by including its name and optional argument(s) in a statement
• Example:
– $game = param (‘Game’);
– param function is called and the argument is the Game key
Functions
• Each function has a specific task
– After the function has completed, a value is returned to the statement that called it
– The statement does not have to use the return value of the function
• function:
– Syntax:
Functions
• function:
– function header:
• Begins with subkeyword, space, function name, space, opening brace ({)
– Same rules for naming functions as naming variables – Variable names should be easy to understand
– function footer:
• Closing brace (})
– return statement:
• Optional
– If there is no return statement, the function returns the value of the last statement it processes
• Can return multiple value(s)
• The function is terminated after the value(s) are returned
The Dombrowski Company Script
– 2 calls to user‐defined functions:
• display_error_page();
• display_acknowledgement();
• If there are no argumentsto pass to a function, following the function name is anempty set of parentheses.