Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl



Similar documents

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

7 Why Use Perl for CGI?

CGI Programming. What is CGI?

Exercise 1: Python Language Basics

PHP Debugging. Draft: March 19, Christopher Vickery

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

VB.NET Programming Fundamentals

Top 72 Perl Interview Questions and Answers

A Simple Shopping Cart using CGI

Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

Perl/CGI. CS 299 Web Programming and Design

PL / SQL Basics. Chapter 3

PHP Tutorial From beginner to master

Data Integrator. Pervasive Software, Inc B Riata Trace Parkway Austin, Texas USA

Web Development. Owen Sacco. ICS2205/ICS2230 Web Intelligence

Moving from CS 61A Scheme to CS 61B Java

6. Control Structures

6.170 Tutorial 3 - Ruby Basics

10CS73:Web Programming

#!/usr/bin/perl use strict; use warnings; use Carp; use Data::Dumper; use Tie::IxHash; use Gschem 3; 3. Setup and initialize the global variables.

Introduction to Python

Python Lists and Loops

Programming in Perl CSCI-2962 Final Exam

TCP/IP Networking, Part 2: Web-Based Control

Computer Programming C++ Classes and Objects 15 th Lecture

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Data Tool Platform SQL Development Tools

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

NewsletterAdmin 2.4 Setup Manual

Variables, Constants, and Data Types

Welcome to Introduction to programming in Python

Training Module 4: Document Management

Who s Doing What? Analyzing Ethernet LAN Traffic

DTD Tutorial. About the tutorial. Tutorial

Computational Mathematics with Python

Excel: Introduction to Formulas

10.1 The Common Gateway Interface

Dialog planning in VoiceXML

Computational Mathematics with Python

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

JavaScript: Control Statements I

Microsoft Windows PowerShell v2 For Administrators

TIP: To access the WinRunner help system at any time, press the F1 key.

ESPResSo Summer School 2012

Qlik REST Connector Installation and User Guide

Command Scripts Running scripts: include and commands

Sources: On the Web: Slides will be available on:

Web development... the server side (of the force)

SnapLogic Tutorials Document Release: October 2013 SnapLogic, Inc. 2 West 5th Ave, Fourth Floor San Mateo, California U.S.A.

Chapter 2: Elements of Java

Introduction to Python

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

C Language Tutorial. Version March, 1999

Job Cost Report JOB COST REPORT

Visual Logic Instructions and Assignments

Windows PowerShell Essentials

Limitation of Liability

Hands-On UNIX Exercise:

Python Loops and String Manipulation

CS Unix Tools & Scripting Lecture 9 Shell Scripting

SAPScript. A Standard Text is a like our normal documents. In Standard Text, you can create standard documents like letters, articles etc

Hands-on Exercise 1: VBA Coding Basics

Moving from C++ to VBA

Exercise 4 Learning Python language fundamentals

ACCELL/SQL: Creating Reports with RPT Report Writer

Litigation Support connector installation and integration guide for Summation

Introduction to Matlab

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

The C Programming Language course syllabus associate level

13 Classes & Objects with Constructors/Destructors

Informatica e Sistemi in Tempo Reale

Selecting Features by Attributes in ArcGIS Using the Query Builder

Writing Control Structures

Understand for FORTRAN

Chapter 5 Names, Bindings, Type Checking, and Scopes

Using Functions, Formulas and Calculations in SAP BusinessObjects Web Intelligence

Designing and Implementing Forms 34

DeltaPAY v2 Merchant Integration Specifications (HTML - v1.9)

Lecture 2 Notes: Flow of Control

Lecture 5: Java Fundamentals III

Creating Cost Recovery Layouts

Kiwi SyslogGen. A Freeware Syslog message generator for Windows. by SolarWinds, Inc.

Shell Scripts (1) For example: #!/bin/sh If they do not, the user's current shell will be used. Any Unix command can go in a shell script

Thoroughbred Basic TM ODBC Client Capability Customization Supplement

Using This Reference Manual Chapter 1 to Issue ACL Commands

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

MATLAB Programming. Problem 1: Sequential

Access 2010: Creating Queries Table of Contents INTRODUCTION TO QUERIES... 2 QUERY JOINS... 2 INNER JOINS... 3 OUTER JOINS...

Perl for System Administration. Jacinta Richardson Paul Fenwick

Administration Guide. BlackBerry Resource Kit for BES12. Version 12.3

BASH Scripting. A bash script may consist of nothing but a series of command lines, e.g. The following helloworld.sh script simply does an echo.

Computational Mathematics with Python

Transcription:

First CGI Script and Perl Perl in a nutshell Prof. Rasley 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 1

Parsing Data The param function accesses the value associated with a key param is part of the standard features of CGI.pm param(key) where key is in single or double quotation marks 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: Scalar variable can store one value» Example: number or string Array variable can store lists or sets of values Hash variable 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); 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 2

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 Default method 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 3

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 4

Hash Variables Accessing the hash: If a key has a space: Use single or double quotation marks within the braces $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 foreach element (group) { One or more statements processed per element in group The foreach and for Statements 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 for: The for statement is used to repeat one or more statements as long as the loop condition is 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 5

The foreach and for Statements for: 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 foreach will be used to process each member of the @sysletter array Creating and Opening a File 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 while and until statements while statement: Used to repeat a block of instructions while a condition is true 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; 5000 200 100 3 Result: while and until statements until statement: Used to repeat a block of instructions until a condition becomes true 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; 5000 200 100 3 Result: 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 die message 6

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 Syntax: arrayname = <filehandle>; Reading Records into an Array More on foreach 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 @records = <INFILE>; 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 7

Removing the Newline Character Chomp function can be used to remove the newline character (\n) from the end of a record Syntax: chomp (variable); 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); 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 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 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 8

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 9

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 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); @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 $size = @errors; Now, $size will be equal to the number of scalar variables in the array The scalar function Syntax: scalar (array); 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.pm file Code for push is stored in perl/perl.exe 10

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 $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: Functions function: function header: Begins with sub keyword, 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 arguments to pass to a function, following the function name is an empty set of parentheses. How do we get at the function arguments? @_ is a special array that contains arguments passed to that function For example, if one argument is passed, can access it with $_[0] Perl creates this array automatically for us when we define functions The exit; statement exit; terminates the script Stops the script from processing further instructions Not required, but a good programming practice The script will terminate after the statements have completed 11

The Scope of variables Environment Variables If a variable is declared within a function, it is only available to that function Many programmers consider it poor programming to have a function assign values to variables declared in the main part of the script More difficult to debug and troubleshoot Series of hidden keys and values that the Web server sends to a CGI script when the script is run Can find out more information about the web server, user, and the user s browser through environment variables Stored in the %ENV hash Environment Variables 12