<<

Lecture #1 Introduction to

Introduction Perl is acronym of “Practical Extraction and Report Language”. It is a developed by Larry Wall in the late 1987 as a -based report language. However, it has evolved to be one fo the popular Web programming languages. According to the Perl.org site, which develops and maintains the language, Perl is “intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). Its major features are that it is easy to use, supports both procedural and object-oriented (OO) programming, has powerful built-in support for text processing, and “has one of the world’s most impressive collections of third-party modules.”

As of the time this lecture note is written, Perl 5 is the latest stable version. The latest major stable revision of Perl 5 is 5.24.0, which is released in May 09, 2016. There is, however, Perl 6 which is still under development. According to the Perl.org web site, Perl 6 is a sister language, part of the Perl family, not intended as a replacement for Perl 5, but as its own thing - libraries exist to allow you to call Perl 5 code from Perl 6 programs and vice versa. The final release date of Perl 6 is unknown.

Tools need for Perl is not part of Windows . Students using Windows OS need to built the this class “toolkit” individually in order to complete all the learning activities of this course. The toolkit includes: (a) a Perl distribution, (b) a web server, () a generic text editor, and () an optional but recommended USB flash drive (with 2GB of free speace). While a nearly-zero cost solution is provided by the instructor as part of the learning activities in this lecture, this section will explain why the toolkit is required.

Perl distribution is available for a wide variety of platforms, including Windows, , and Mac. This lecture note is written based on Windows operating systesm. Students will need to download the either the 32-bit or 64-bit binary code applicable for their platforms and install Perl. The official site to download Perl is http://www.perl.org/. Due to the need to discuss Perl for Web programming, the instructor chooses to use XAMPP which is a handy tool with Perl included.

XAMPP is an open-source web server package that works on various platforms. It is actually an acronym with X meaning “cross” platform, “A” for Apache HTTP server, “M” for MySQL, “P” for PHP, and “P” for Perl. XAMPP was designed to help webpage developers, programmers, and designers check and review their work using their computers even without connection to the web or internet. The latest version of XAMPP is available for downloading at https://www.apachefriends.org/index.html. By the way, the entire XAMPP can be installed into and executed from a USB flash drive.

= Apache + MySQL + PHP + PERL

1

The good news is: Perl can run in most major operating systems, including Linux/ Unix, , Mac OS X, and others. Perl also supports most of the web server software including Apache, Microsoft Internet Information Server, Personal Web Server, Netscape, iPlanet servers, and many others. However, it is not techinically practical for the instructor to provide every student a functional Web server. In the past, students need to download and install a Web server application, such as Apache. Then, each student need to: (a) download and install Perl installer, (b) activate supports for Perl, and (c) modify the server’s configuration files in order to recognize Perl script files before they can write and test Perl scripts. On the other hands, in order to learn how a Perl server works with MySQL server in order to build a data-driven site, students also need to download and install the MySQL software, which is a popular choice of database management system (DBMS) used in the World Wide Web.

Thanks to the generosity of ApacheFriends.org which provides XAMPP for free, students are now able to execute PHP scripts without all the above mentioned preparations. XAMPP is a free and open source cross-platform web server package, consisting mainly of the Apache HTTP Server, MySQL database, and interpreters for scripts written in the Perl. Throughout this course, students will be using XAMPP to test and execute Perl scripts. The lastest version of XAMPP can be downloaded at https://www.apachefriends.org/.

With XAMPP installed, each student’s personal computer (including laptop) becomes an individual web server that can interpret PHP codes and is able to execute query statements to retrieve data from a MySQL database.

XAMPP = client + Web server + PERL server + MySQL server

The following figure illustrates the role MySQL plays. Perl scripts is the intermediary between the web browser and the MySQL server. The browser is the data requester, while MySQL is the data provider. The communication between the browser and the web server is handled by Perl. Likewise, the communication between the web server and MySQL is done by Perl as well. Interestingly, the user interface between the user (human) and the web server must be defined with HTML (Hypertext Markup Language), which is a standardized system for tagging text files to achieve font, color, graphic, and hyperlink effects on World Wide Web pages.

dynamic web

web content data web manipulation browser MySQL HTTP request server database

In a nutshell, a dynamic web site can be constructed by using Perl to build the application, while using HTML to define the web content layouts. The following illustrates the relationship between Perl and HTML. One can say that HTML is at the human layer, while Perl is only at the Perl. The good news is: Throughout this course, students will focus on the learning of Perl coding, not the building of fancy-looking web sites using HTML and CSS (cascade style sheet). After all, this is a web programming course, not a web development course.

2

In a nutshell, a dynamic web site can be constructed by using Perl to build the application, while using HTML to define the web content layouts. The following illustrates the relationship between PERL and HTML. One can say that HTML is at the human layer, while Perl is only at the Perl. The good news is: Throughout this course, students will focus on the learning of PERL coding, not the building of fancy-looking web sites using HTML and CSS (cascade style sheet). After all, this is a web programming course, not a web development course.

HTML human user

PERL machine

In this class, due to the barriers for the instructor to build a server that allows students to upload scripts and test these scripts with the server, XAMPP is probably the best alternative. Students will install a copy of XAMPP, which is a scaled-down version of Apache Web server, on a local machine (or a USB flash drive).

The next few sections will discuss how Perl dynamically generate output for command-line interfaces (such as the Microsoft Command Prompt and Linux Terminal) and web broswers. By the way, a command line interface (cli) is a user interface to a computer’s operating system or an application in which the user responds to a visual prompt by typing in a command on a specified line, receives a response back from the system, and then enters another command, and so forth. Throughout this course, the instructor chooses to use Microsft Command Prompt for demonstration.

Microsoft Windows [Version 10.0.14393] (c) 2016 Microsoft Corporation. All rights reserved.

C:\Users\user>

As a matter of fact, programmers can run Perl from a graphical user interface (GUI) environment as well. Some use Padre (a Perl IDE); others use Eclipse Plugin EPIC (Perl Editor and IDE for Eclipse if you are familiar with Eclipse). However, throughout this course, a generic text editor like Microsoft Notepad is good enough.

Perl supports several file extensions; however, programmers typically use .pl for regular Stand- alone Perl scripts and .pl or .cgi for Web scripts, while Perl modules use .pm. A Perl “module” is a set of related functions in a single library file with .pm extensions. Throughout this course, students will mainly create stand-alone Perl scripts use the .pl extension.

What is a Perl Perl is a scripting language. All Perl programs do not need to be compiled into self-excutable program? programs (such as .exe). They stay as text-based script files designed to be read by the Perl . Each time when a Perl script is called for , it is the Perl interpreter that converts the script file contents to machine codes (binary codes). The text-to-binary convesrsion is done each time when the script files are read. Unlike most programming languages (such as C++), Perl script files are not required to be compiled into self- programs. However, there are some utilities that can compile Perl scripts into standalong (read for http://www.nicholassolutions.com/tutorials/perl-PAR.htm details). The following figure illustrates how a Perl script is interpreted and its two possibly routines of output.

3 Command-line interface Perl Perl scripts interpret Web server Web browser (Apache) (GUI)

In a nutshell, Perl scripts perform a combination of three primary tasks, Inpute, Processing, and Output, known as the I-P-O model. The following is a simple Perl script that performs both processing and output. It generates a text message as output: Hello, world!. In this program, the instructor did not use any control structure (such as if..else or for loop); therefore, all its statements will be read sequentially (in a line-by-line manner). By the way, Perl scripts do not need to have a main() method as entry point.

#!/usr/bin/perl print "Content-Type: text/html\n\n";

print "Hello, world!";

The print construct is a built-in tool that returns values of a collection of objects. A built-in tool is created by the programmers who create the Perl language for other programmers to use. The term a collection implies that each “print” can displays values of two or more objects. In the following following, values of three individual objects are displayed by exactly the same “print” construct.

print "Hello," , "World!" , " Welcome to Perl";

“Objects” can be anything that contains values or produces values. In the following example, $name is a variable, and (4*3) is an expression. A Perl variable is used to store a value temporarily in a program. A Perl expression is a phrase that can contain ordinary scalar values, variables (like $x or $y), and operators (such as addiion, subtraction, multiplication, and division).

$name = "Taylor Swift";

print "Welcome, ", $name, (4*3);

In Perl, “print” has two forms: construct and function. When being used as a construct, string literals are surrounded by a pair of quotes. When being use as a function, objects must be enclosed by a pair of paretheses. Since the above code demonstrated how to use “print” as a construct, the following demonstrates how to use it as a function.

#!/usr/bin/perl print "Content-Type: text/html\n\n";

print("Hello, world!");

The following is another example. It enclosed three individual objects within the paretheses.

print("Hello," , "World!" , " Welcome to Perl");

Interestingly, Perl is a scripting that was originally designed to run in a Unix environment. The first line of every Perl script is the so-called “Shebang”, which is the character sequence consisting of the characters number sign and exclamation mark (#!) followed by path to the interpreter. When a Perl script is run as a web program, “shebang” serves as an interpreter directive to specify which interpreter program should be call on duty. Interestingly, when a Perl script is running in Microsoft’s Command Prompt, “Shebang” is not required, yet “Shebang” is required by the Linux command-line interface. The above script is meant to be

4 executed in a Unix/Linux envrionemnt; therefore, its “Shebang” is defined in Unix convention. By the way, Linux users need to check their system setting to determine the correct path to the Perl interpreter. The above script assumes the path is:

#!/usr/bin/perl

Throughout this course, the sample codes will be written for executing in a Windows environment, such as Windows 10 or 8. In order to run the script with a Microsoft Windows operating system, the Shebang must follow Windows’ path convention, which is:

#!"driveName\paths\perl.exe"

The following table lists main differences between Windows and Unix conventions.

OS Windows Linux Device name Drive name must be a letter, such No letter in use. as “E” or “F”, followed by a colon (:).

Name of File extension is required, such as File extension is not required. The file interpreter perl.exe, which must have “.exe”. name is simply, perl.

Path layer Layers are separated by “\”. Layers are separated by “/”.

Throughout this course, the instructor will use XAMPP, which places the Perl interpreter in the “X:\xampp\perl\bin\” directory, where “X” is the drive name (such as “C” or “F”) of the device (e.g. a USB flash drive) in which XAMPP resides. With this premise, the Perl interpreter for Windows OS (perl.exe) is in the “X:\xampp\perl\bin” directory; therefore, the “Shebang” should be:

#!"X:\xampp\perl\bin\perl.exe" Replace X with the correct drive name

In order to run the above Perl script in a Windows OS environment, it is necessary to replace the Unix-based “Shebang” to the following.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "Hello, world!";

Throughout this course, output of Perl scripts will be displayed on a web browser (as a graphical user interface) and occasionally in Microsoft Command Prompt (a command-line interface). Web browsers are designed to read and process HTTP contents. One of the requirement is the use of MIME (Multipurpose Internet Mail Extension) as a standard for formatting files of different types, such as text, graphics, or audio, so they can be sent over the Internet and seen or played by a web browser or e-mail application. In order for a Perl script’s generated results to be readable to a web browser, it is necessary to declare the MIME type as HTML content. The following is the most direct way, and will be used throughout this course.

print "Content-Type: text/html\n\n";

Without the MIME declaration, the web browser will display an error message similar to the following.

5

Every Perl statements must end in a semi-colon (;). A Perl script as a program consists of one or more statements. The following will cause an error message due to the missing semicolons (;). The error message is: syntax error at ... line3, near "print"...had compilation errors.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "Hello, world!" print "Welcome to Perl"

The correct code should be:

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "Hello, world!"; print "Welcome to Perl.";

While the above scripts demonstrates how to perform processing and output. The following demonstrates how to use the tool, which stands for standard input, to take user input from the keyboard in a command-line interface. By the way, throughout this course, most of the user inputer will be processed by HTML forms.

#!"X:\xampp\perl\bin\perl.exe" print "Enter your full name: "; $input = ; print("Welcome, $input");

“Input” does not have to come from a user entry. An input can be generated by the program. In the following example, the instructor calls the Perl’s localtime() function and uses it as input.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

$dt = localtime(); print ("Local date and time: ", $dt)

The following illustrates how the above script can be executed in the Microsoft Command Prompt, assuming the script name is “1.pl”, the device drive name is “F”, and the user type “Taylor Swift” and press [Enter].

F:\cis245>perl 1.pl Enter your full name: Taylor Swift Welcome, Taylor Swift

A Perl script consists a well-developed body and frequently contains control structure, such as if..else, for decision making. A later lecture will discuss control structure in details. The

6 following is a simple Perl script that demonstrates how a Perl program makes decisions. By the way, in Perl, a variable must have a prefix “$”, such as $i. A variable is used to store a non-fixed value temporarily in a Perl program.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

$i = 5;

if ($i > 5) { print "Good."; } else { print "OK."; }

The following demonstrates how Perl’s repetition structure works. A later lecture will discuss repetition structure in details.

#!"F:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

for ($i=1; $i<=6; $i++) { print "heading ", $i, ""; }

A sample output of the above code is:

The following is a sample code that demonstrates how to use an HTML form to collect user input. A later lecture will disucss abou this topic in details.

#!"X:\xampp\perl\bin\perl.exe" use CGI qw(:standard);

print "Content-type: text/html\n\n";

print "";

if (!param) { print "

\n"; print "Enter your full name: "; print "
"; }

else { $fname = param('fname'); print "Welcome, $fname!!"; }

print "";

A sample output looks:

7

and

In the next few sections, the instructor will discuss some linguistic issues to help students build a solid foundation for the rest of lectures.

White space The collection of spaces, indents, tabs, and new lines separating one object in a Perl script from vs. blank space another is known as “white space”. In Perl, white space outside quotes (such as double quotes) are irrelevant and are ignored. The following will produce the same result as the above. By the way, white space is often used to make a Perl script more human-readable.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "Hello, world!" ; print "Welcome to Perl." ;

The term “white space” does not apply to “blank space” of a string object. “Blank space” inside as string are are enclosed by a pair of quotes, such as the blank space in “Taylor Swift” and “Pennsylvania State Unviersity – College Park”. In a string literal, “blank space” is a character that has not visible shape, they cannot be ignored. The following demonstrates how “blank space” are not ignored.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "Hello, "; print "Taylor Swift "; ; print "Welcome to Perl." ;

A sample output in the command-line interface looks:

Hello, Taylor Swift Welcome to Perl.

Interestingly, web browsers are designed to purposely ignore “blank space” except the one between every two words. The output of the above code in a web browser looks:

8 In the following example, all the white space insie the parentheses are ignored by the Perl interpreter.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print( "

", "Hello, world!", "

");

Comma in the In Perl, print is a very special tool. In the following code, the string literal is “Hello, print World!”, which contain a comma (,) as a character. Again, the comma (,) inside the double quotes is a character of the string and is used to separate the word “Hello” and the word “world!”. In this case, this particular comma does not have any linguistic meaning in Perl.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "Hello, world!";

No meaaing in Perl.

Interestingly, print also uses the comma (,) sign as delimiter to mark the separation of objects. In the following, the instructor purposely uses commas to break a long statement, “

Hello, world!

”, into three lines. In this case, each of the three commas have linguistic meaning in Perl.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "

", "Hello, world!", "

";

This is often a confusing issue to newbies. In the above example, the comma between Hello and World is a pure comma (no linguistic meaning in Perl); however, the rest three comma signs are the delimiter that marks the separation of objects. As a general rule, commas inside quotes are pure comma, while commas outside quotes are demiliters. The above code is exactly the same as the following.

#!"F:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "

Hello, world!

";

In the following example, print is used a function. Yet, the general rule still applies. commas inside quotes are pure comma, while commas outside quotes are demiliters.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print( "

", "Hello, world!", "

");

The above code is exactly the same as the following.

print("

", "Hello, world!", "

");

9

Quote, quote, In Perl, print output the value of objects. Since a variable is a value-holding object, programmers quote can assign the value to a variable, such as $str1, $str2, $x, and $y, and then print their values, as shown in the following code.

#!"F:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

$str1 = "

I am enclosed by double quotes

";

$str2 = '

I am enclosed by single quotes

';

$x = 12;

$y = 17/5;

$n = undef;

print $str1, $str2, $x, $b;

Interestingly, value of $str1 is assigned with double quotes, value of $str1 is assigned with single quotes, values of $x and $y are not enclosed by any quotes. As a general rules, only string literals must be enclosed by quotes, numerical value should not be encloded by quotes. A “string” is just a combination of characters, regardless how it looks to a human reader. In the above example, $x, $y and $n are not string object. By the way, “undef” is a special data type means “not defined”. A later lecture will discuss data type in details.

In this lecture, student needs to pay attention to the differences of single and double quotes when using them to enclose strings. The instructor uses “pure string” and “string with hidden data” to explain the concept. • A pure string is an object that is simply a combination of characters like “Taylor Swift”. • A string with hidden data means there are some possibly Perl object enclosed by a pair of quotes, such as “Welcome, $name!”.

When an object is a pure string, the use of double or single quotes makes no difference.

$name = "Taylor Swift";

or

$name = 'Taylor Swift';

As a matter of fact, Perl takes the single-quoted strings “as is” and interpolates the double- quoted strings. The term “to interpolate” means the content must be interpreted before outputting them. In the following example, $name inside the single quotes are treated as pure characters, while $name in double quotes are interpreted as Perl variable, the Perl interpreter will substitutes such variables with variables’ values.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

$name = 'Taylor Swift';

print "Welcome, $name!"; ### Welcome, Taylor Swift!

print 'Welcome, $name!'; ### Welcome, $name!

Character combinations in double quotes will be checked for linguistic definition. Character combinations in single quotes are treated as characters. In the following , “\t” and “\n” are escape

10 sequence that means “the tab” and “new line” respectively. Inside double quote, “\t” and “\n” will take effect, yet, they are ignored inside single quotes.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "Apple\tOrange\n"; ### Apple Orange

print 'Apple\tOrange\n'; ### Apple\tOrange\n

Using the Perl Once installed and correctly configured, XAMPP can make a student’s computer behave like a interpreter Web server. However, in order to execute a Perl script with XAMPP-Apache server, which is (provided by what you will use throughout this course, every student needs to clearly specific the path of XAMPP) the Perl interpreter. XAMPP comes with a perl interpreter stored in the “X:\xampp\perl\bin” directory where “X” is the drive name. For example, if the USB drive that hosts the XAMPP- Apache server is the F: drive of Windows operating systems, and the “perl.exe” file resides in the “F:\xampp\perl\bin” directory, then the Shebang line must be correctly specified, as shown below.

#!"F:\xampp\perl\bin\perl.exe" print "Hello, world!";

This requirement is rigidly enforced, you must match the drive name and the path; otherwise, you will receive the following error message stating “The server encountered an internal error and was unable to complete your request”.

With XAMPP installed to a local drive (or a USB flash drive) of a Windows OS machine, you can run the Perl interpreter on the Command Prompt, as shown below.

C:\Users\D002127465>F:

Windows 10/8 Command Prompt typically displays the user’s home directory which is the username under the “\Users” directory, such as “C:\Users\D002127465”. If the F:\ drive (presumably the USB flash drive) is where the Perl interpreter resides, type F: and press [Enter] to change to the F: drive.

F:\>cd xampp\perl\bin

If the Perl interpreter is stored in the “xampp\perl\bin” directory, type cd xampp\perl\bin and press [Enter] to change to the directory. Under the “bin” directory, type perl –v to display the version of Perl interpreter, as shown below.

F:\xampp\perl\bin>perl -v

11 This is perl 5, version 16, subversion 3 (v5.16.3) built for MSWin32-x86-multi-thread

Copyright 1987-2012, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on this system using "man perl" or "perldoc perl". If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page.

To test a Perl script named “test.pl” that resides in the “X:\xampp\htdocs\myperl” directory, students can start with opening a Command Prompt, and then swtich to the correct drive.

C:\Users\D002127465>F:

It is necessary to use the cd command of DOS to change to the “X:\xampp\htdocs\myperl” directory.

F:\>cd f:\xampp\htdocs\myperl

Assume that you have downloaded the XAMPP installer and completed the installation procedures, you can access the Perl interpreter through the Command Prompt. The path is x:\xampp\perl\bin (where x is the drive name such as F: or C:). Students can optionally create a batch file named “getperl.bat” with the following statement and save it in the USB drive that hosts the XAMPP-Apache server. Each time before you run the Perl interpreter in the Command Prompt, call this “getperl.bat” file to reset the path.

@echo off path=%path%;%CD%xampp\perl\bin;

Basic One unkown drawback of using web server to test the Perl script is that any error message debugging generated by the Perl interpreter will be ignored by the web server. The web server simply display an error message that does not provide much reference to the error. One way to detour this problem is to use the command-line interface to debug the Perl script. In the Windows environment, the file name of Perl interpreter is “perl.exe”. It can be called from the Command Prompt using either “perl.exe” or “perl”. The following is the simplest syntax to run a Perl script which runs the Perl script from a given file.

perl scriptName.pl

The following demonstrates how to execute a Perl script named “test.pl” that resides in the “X:\xampp\htdocs\myperl” directory, from Command Prompt.

X:\xampp\htdocs\myperl>perl test.pl

Use the “-c” option when running Perl to use this tool. The “–c” option “only check for syntax errors, then exit”, but it does not generate the output. For example:

X:\xampp\htdocs\myperl>perl -c test.pl test.pl syntax OK

The following table lists some commonly used options.

Option Description -w Enable many useful warnings

12 -W Enable all warnings -t Enable tainting warnings -T Enable tainting checks -U Allow unsafe operations -X Disable all warnings -e program run Perl script sent in as program

The “-w” option is the default option. This option tells Perl to check your script for syntax errors and to execute your script.

X:\xampp\htdocs\myperl>perl -w test.pl Content-Type: text/html

Hello, CIS245!

It makes no difference whether or not to specifiy with the “-w” option. This lecture note intentionally omits the “-w” option by simplifying the above step to perl test.pl because the “-w” option is the default.

X:\xampp\htdocs\myperl>perl test.pl Content-Type: text/html

Hello, CIS245!

Perl interpreter checks the syntax (or grammar of the language); therefore, it can help to debug scripts. The following is a sample script with error, which is named err.pl.

#!"X:\xampp\perl\bin\perl.exe"

print "Test Page"; print "Hello World!" print ""; add the missing ;

In the Command Prompt, type perl –c err.pl and press [Enter]. The debugger catches the error and displays:

X:\xampp\htdocs\myperl>perl –c err.pl Syntax error at err.pl at line 4, near "print" err.pl has compilation errors.

Modify the source code by adding the missing semicolon sign (;):

#!"X:\xampp\perl\bin\perl.exe" print "Test Page"; print "Hello World!"; print "";

Check the code again.

X:\xampp\htdocs\myperl>perl –c err.pl err.pl syntax OK

Perl Console Perl was originally created as a scripting language for Unix environment; therefore, it has the Applications nature to support command-line user interface. Applications for Unix-based command-line is oftern referred to as “console applications”. Although most applications students will create throughout this course are GUI (graphical user interface) applications, not console applications, it is an old school convention that students at least have a chance to understand to what console applications. The following is a sample.

13 #!"X:\xampp\perl\bin\perl.exe" print "What is your name? "; $str = ; print "Welcome, $str!";

By declaring a scalar variable, such as $str, and setting it equal to , the variable will keep whatever will be typed by our user at the command prompt. Literally stands for “standard input.” It tells the Perl interpreter to read one line from the standard input (the keyboard), where a line is defined to be a set of characters terminated by a new line. It is necessary to note that has a format similar to HTML tags, but it is not an HTML tag.

The following illustrates the result of execution. Notice that the exclamation sign (!) is placed in a new line. The above code requires users to enter a string, and then press the [Enter] key to complete the execution. Ironically, the [Enter] key is also taken by the as the last part of user entry.

F:\xampp\perl\bin>perl test.pl What is your name? Jennifer Lopez Welcome, Jennifer Lopez !

In the following example, the chomp() function removes any trailing string that corresponds to the current value of user entry. The instructor uses it to remove the unwanted [Enter] key.

#!"X:\xampp\perl\bin\perl.exe" print "What is your name? "; $str = ; chomp($str); print "Welcome, $str!";

The following illustrates the result of execution.

F:\xampp\perl\bin>perl test.pl What is your name? Jennifer Lopez Welcome, Jennifer Lopez!

Interestingly, can be abbreviated by using simple <>; therefore, the following will produce the same result.

#!"X:\xampp\perl\bin\perl.exe" print "What is your name? "; $str = <>; chomp($str); print "Welcome, $str!";

Perl Web Perl is one of the more commonly used languages for building Web applications. Writing Perl Scripting Web scripts requires just a little background in HTML and HTTP requests. In the nut of Web scripting, Perl is used as CGI (Common Gateway Interface), meaning this Perl script is a dynamic contact point at the server side to the web browser. The term “dynamic” indicates that this Perl script can generate its output in HTML form and deliver them over the Web from the server to the web browser. Perl programmers can learn to handle this requirement through a hands-on experiment, and the following is one. It is a simple Perl script, yet it does not qualify for being a Perl Web script. If you upload this script file to a web server, and attempt to access it using a web browser through the Web, you will encounter an unfriendly error page.

#!"X:\xampp\perl\bin\perl.exe" print "Hello, CIS245!";

The following is a sample output on the browser. By the way, Web servers commonly require

14 that your script have a specific file extension, such as .pl, .plx, or .cgi. In this class, the instructor chooses to use the .pl extension.

As discussed in a previous section, this error is caused by “missing HTTP header” which is MIME issue. The communication between a browser and the Web server requires the specification of HTTP headers which provide the information, in the form of a text record, that contain the details of what the browser wants and will accept back from the server. The request header also contains the type, version and capabilities of the browser that is making the request so that server returns compatible data. To eliminate this error, Web servers require programmers to declare the content type, particularly the following one.

print "Content-Type: text/html\n\n";

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner. As to this sample script, programmers need to add the following bold line to the above code. Additionally, it is necessary to replace “X” with the correct drive name.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "Hello, CIS245!";

The output now looks:

A regular Web page is a text file that uses HTML tags to format its contents. HTML stands for Hyper Text Markup Language. It is a markup language. A markup language is a set of markup tags. A tag describes formatting and appearance of document content. A web page is, thus, a combination of HTML tags and document content. The following is a example of a Web page.

sample page

Welcome to CIS245!

15 The declaration is an HTML5 requirement that helps the browser to display a web page correctly. There are few kinds of declarations based on the version of HTML. This course chooses to following HTML5 format. • HTML 4.01: • XHTML 1.0:

All the HTML tags are combinations of characters. For example, the

tag is a combination of the <, h, 1, and > characters (four separate characters). HTML tags are keywords (tag names) surrounded by angle brackets like . In most of the cases, HTML tags work in pairs: a start tag and an end tag. The end tag is written like the start tag, with a slash before the tag name, such as . To underline a sentence, use both and tag to enclose the sentence, as shown below.

This line is underlined. This line is not.

An HTML page have structure. It takes and tag to declare the beginning and the end of HTML content. Inside and , programmers use and to define the viewable contents of a Web page. The body area is where you place all the contents for viewers to see. Yet, all the web contents must be arranged insider the body area. The following is another simple Web page. The instructor purposely use indents to indicate the layer of tags.

This a heading

This is a paragraph.

This is another paragraph.

Since Web page is a text file and all its contents are simply characters. Perl programmers can uses the Perl print function (which also work like a construct) to return HTML contents to a browser by treating all of them as character-based literals (known as string). In the following code, the print function return a line of string to the browser.

#!"X:\xampp\perl\bin\perl.exe" Replace X with the correct drive name print "Content-Type: text/html\n\n";

print ""; print ""; print "

Hello CIS245!

"; print "";

The above code produces the following content (the gray line represent a blank line in the source code), which is a HTML-formatted content that is good enough for a web browser to read, understand, and display the HTML content as a Web page.

Content-Type: text/html

Hello CIS245!

16 A sample output looks like this:

Another way to “print” HTML code is to declare a variable, such as $code, and append all the HTML code to it. The appending is done by the concatenation operator (.=) which will be discussed in a later lecture. The following example illustrates how this approach works, and it produces the same output as the above one.

#!"X:\xampp\perl\bin\perl.exe"

$code = "Content-Type: text/html\n\n"; $code .= "Hello, CIS245!";

print $code;

The following is a template code for Perl Web scripting. You can use it to test your Perl code with XAMPP.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print ""; print "";

## add Perl code here ###

print "";

Using Perl A Perl Module (sometimes called pragma) is a collection of related and data Modules designed to be used by other programs or modules. A pragma is a module which influences some aspect of the compile time or run time behavior of Perl, such as strict or warnings.

Modules are defined in separate files and use the package keyword to define a for the data and subroutines in that module file. For example, the strict.pm module is a Perl pragma used to restrict unsafe constructs. The synopsis is:

use strict;

The use directive specifies the file system path of a module (or a sub module); therefore, Perl can find the module and include it to the namespace.

A module can be a simple collection of subroutines, not defining a class. Such modules are referred to as libraries. A class is a user-defined data type. Classes are defined in modules using special constructs that allow you to create variables of that type. The subroutines in these modules are referred to as methods.

An object is a variable that belongs to a particular class. It contains its own private data that can be operated on by the methods defined in the class. The object is called an instance of its class. For example, a Perl module named Person.pm may contain a class named Person. You can use it to create a new object called "Jennifer Lopez", which has methods like dance(), sing(), and smile().

17 Each Perl module provides a set of classes and methods, generally known as members of the module. For example, the CGI.pm module is a very popular Perl module used in web programming. The instructor believes it is a good module students must learn. A later lecture will discuss this module in details. For now, consider the following Perl script as a preview.

#!"X:\xampp\perl\bin\perl.exe" use CGI qw(:standard);

print header, start_html('CIS245'), h1('Hello world!'), end_html;

The above code produces the following HTML outputs. Notice the “header” methods generates HTML code that complies with XHTML and HTML5 standards.

CIS245

Hello world!

The output, when processed by a web browser, looks:

The CGI.pm module provides methods such as header, start_html, h1, and end_html to generate HTML outputs. These methods are members to the CGI.pm module. The line use CGI qw(:standard); means to import all the "standard" subroutines in the CGI module to the current namespace. The qw() function is a Perl function called “quote word”. It tells the Perl interpreter to treat the word as if it were entered in single quotation marks.

Perl uses the double colons (::), similar to Visual C++, as the file system path separator. A Module called Shape::Rect corresponds to a file named Shape/Rect.pm relative to a module library directory.

In the following example, the use HTTP::Date; line indicates that Perl interpreter must include the HTTP/Date.pm file to the script file, so all the members in Date.pm module can be used in this script handle date and time values.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

18 use HTTP::Date; my ($date, $time) = split(" ", HTTP::Date::time2iso()); my ($hour, $min) = split(":", $time); print "Current time is: $hour:$min\n
"; print "Current date is: $date\n\n"; exit;

The output looks like this:

There are few useful modules you will frequently see in this class. They are: • File::Find - Recursively loop through all files in a given directory. This is a library-style module. • DBI.pm - Send SQL queries to a relational database and process results. Requires the appropriate DBD module (e.g.: DBD::oracle, DBD::mysql).

A Perl-enabled web server may not always have every Perl module available. You can simply upload the module files, such as CGI.pm, to the server (usually under the cgi-bin directory) and you are ready to use them. Module files are text files that looks similar to:

package File::Find; use 5.006; use strict; use warnings; use warnings::register; our $VERSION = '1.12'; require Exporter; require Cwd;

# # Modified to ensure sub-directory traversal order is not inversed by stack # push and pops. That is remains in the same order as in the directory file, # or user pre-processing (EG:sorted). #

......

unless ($File::Find::dont_use_nlink) { require Config; $File::Find::dont_use_nlink = 1 if ($Config::Config{'dont_use_nlink'}); }

# We need a function that checks if a scalar is tainted. Either use the # Scalar::Util module's tainted() function or our (slower) pure Perl # fallback is_tainted_pp() { local $@; eval { require Scalar::Util }; *is_tainted = $@ ? \&is_tainted_pp : \&Scalar::Util::tainted; }

19

1;

You can modify the contents of any module file, if necessary. The CGI.pm module, used in this class, was slightly modified by the instructor to fit in Mysite.com’s web server.

A loosely Perl is a loosely designed language compared to C++ or Java. That’s being said, programmers design have more flexibility. On the other hand, a loosely design language also leaves room for language confusing. The print construct is an example because it can behave like a function or a construct. Perl uses the print construct to send output to a destination, such as monitor. The output is usually a combination of characters, known as a string. Perl was originally created by a bunch of Unix people; the format certainly is Unix-favored. In Unix, many commands can be either a construct or a function. It is necessary to know the difference between a construct and a function.

A construct is a command that handles a given string as arguments. For example:

print "Hello, CIS245!";

A function is not a command. It is a pre-programmed sequence of code which performs a specific task, and sometimes called a method. A function consists of a function name followed by a pair of parentheses. The string is held within the parentheses. For example:

print("Hello, CIS245!");

The following two code examples produce the same results, although one in the construct forms, the other in function form.

Construct Example Function Example

#!"X:\xampp\perl\bin\perl.exe" #!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n"; print("Content-Type: text/html\n\n"); print "Hello, CIS245!"; print("Hello, CIS245!");

The output is:

Hello, CIS245!

Common Previous students frequently encountered the “Internal Server Error in Perl” error when they first XAMPP-based learn to write Perl scripts. This is very common error, and is usually caused by typos, missing execution semicolons, missing { or ( signs, etc. Don’t panic! Just be patient and check your source code problems again to “debug”.

When a Perl script fails to execute correctly you will usually see the standard error message:

Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request.

According to Perl, there are numerous potential causes of this error, the most common being: • There is an error in the script. • The correct permissions have not been set. • The file was uploaded in binary mode instead of ASII.

In this course, due to the nature of this lecture note, you should only consider the first cause: “an error in the script”. Throughout the entire course, you do not need to upload scripts to any remote server; therefore, you do not have issues such as “permission settings” and “uploaded in binary mode”. For example, the “couldn’t create child process: 720002: lab1_1.pl” typically means the “SheBang” path is incorrect.

20

Server error! The server encountered an internal error and was unable to complete your request. Error message: couldn't create child process: 720002: lab1_1.pl If you think this is a server error, please contact the webmaster. Error 500 localhost Apache/2.4.2 (Win32) OpenSSL/1.0.1c PHP/5.4.4

Assuming that your thumb drive is recognized as “G” drive; however, you mark “F” in your source code as shown in the following table. Simply change “F” to “G” and you are in business again.

Correct Path Incorrect Path #!"X:\xampp\perl\bin\perl.exe" #!"F:\xampp\perl\bin\perl.exe"

For those who choose to run scripts in a remote server (such as a web server provided by AT&T, Verizon, etc.), you probably need to consult with the webmaster for the permission settings. Assuming you have been instructed by the webmaster to set the correct permissions (usually 755 for “lab1_1.pl”) and uploaded the file in ASII mode, yet the error persists. Then, you should have an error in the script. A “real” Apache-based Perl server usually returns the error message with some indication. For example,

Software error: syntax error at lab1_1.pl line 8, near "print" Execution of lab1_1.pl aborted due to compilation errors.

This error message clearly indicates that a syntax error occurred somewhere near the word "print" on line 8 of your lab1_1.pl script.

Review 1. Why does the following code cause an error message? Questions #!/usr/bin/perl print "Hello, world!"

A. It should be print("Hello, World!"). B. Perl script must include a main() function as entry point. C. The second line must end with a semicolon (;). D. There is nothing wrong.

2. Which of the following will produce a result that is different from others in this question? A. print "

", "Hello, world!", "

";

B. print "

Hello, world!

";

C. $str = "

Hello, world!

"; print $str;

D. $str = "

", "Hello, world!", "

"; print $str;

3. Which is possibly the Shebang statement that can point to the Perl interpreter in order to run a Perl script in a Windows-based computer with XAMPP stored in a USB flash drive? Assuming the USB is recognized as "F" drive.

21 A. #"F:\xampp\perl\bin\perl.exe" B. #!"F:\xampp\perl\bin\perl.exe" C. #"F:\xampp\perl\bin\perl.exe" D. #!"F\xampp\perl\bin\perl.exe"

4. The HTML Content-Type header should read: A. print "Content-Type: text/html\\n\\n"; B. #print "Content-Type: text/html\n\n"; C. print "Content-Type: text/html/n/n" D. print "Content-Type: text/html\n\n";

5. Perl comments are marked with: A. ^ B. # C. ! D.

6. How would you debug a script called "test.pl", if you want to see the errors and execute the script? A. perl -c test.pl B. perl \c test.pl C. perl --c test.pl D. perl /c test.pl

7. Which is the correct way to use a Perl module named “CIS245” in your script? A. using namespace CIS245; B. using System::CIS245; C. use ; D. use CIS245;

8. Which is the correct way to take an user entry from a command-line interface and store it in a variable named "$str" in Perl? A. $str <= STDIN; B. $str => STDIN; C. = $str; D. $str = ;

9. Which option of the perl command can check your script for syntax errors and then exit? A. -d B. -s C. -c D. -w

10. Which is the correct statement to add a Perl module, named "Apple", which is store in the "Fruit" directory to a Perl script? The path is "Fruit/Apple". A. include Fruit::Apple; B. using Fruit::Apple; C. use Fruit::Apple; D. import Fruit::Apple;

22

Lab #1 Introduction to Perl

Preparation #0: “Hide extensions for known file types” option.

(For Windows 10/8 Users Only) (For Windows 7/Vista Users Only) 1. Launch the Windows Explorer. 1. Launch the Windows Explorer. 2. Click “View”. 2. Click “Folders and search options” 3. Check the “File name extension” option. 3. Click the View tab, and then uncheck the “Hide extensions for known file types” option.

4. Proceed to Preparation #1 now.

4. Click OK. Proceed to Preparation #1 now.

Preparation #1: Installing XAMPP 1. Close all the applications that may cause conflicts with XAMPP such as Skype, IIS, Wampserver, VMware, etc.

2. Plug in the USB flash drive and record the drive name (e.g. “F”): ______.

3. Use a browser to go to the https://www.apachefriends.org/download.html site. Download the latest version to the USB drive. As of October 2017, the latest version is 7.1.10.

4. Use Windows Explorer to find the downloaded .exe file (e.g. xampp-win32-7.1.0-0-VC14- installer.exe), and double click on it to launch the installation.

23

5. If the following window pops up, simply click OK.

6. Click Next on the “Setup-XAMPP” window, as shown below.

7. Click Next on the “Select Components” window to select all default. Do not uncheck anything.

8. In the “Installation folder” window, make sure the path is changed to X:\xampp (where “X” is the correct drive name such as “F”). Then click Next.

9. In the “Bitnami for XAMPP” window, uncheck the “Learn more about Bitnami for XAMPP” option, and then click Next.

24

10. Click Next on the “Ready to Install” window.

11. Wait till the installation process completes. It might take up to 20 minutes depending on the system.

12. If the “Windows Security Alert” window pops up, as shown below, simply click “Allow Access”.

13. If the following message (or similar one) appear in a Command Prompt, simply let it completes the configuration updates.

################################################################## # ApacheFriends XAMPP Setup Win32 Version # #------# Copyright (c) 2002-2016 Apachefriends 7.0.8 # #------# Authors: Kat Vogelgesang # # Carsten Wiedmann # ##################################################################

Configure XAMPP with awk for 'Windows_NT' Updating configuration files ... please wait ...

14. Wait till the “Completing the XAMPP Setup Wizard” windows appears. Click Finish to complete the installation process.

25

15. If you are asked to select a language, choose the U.S. flag and click Save.

16. The installation process completes if the “XAMPP Control Panel” appears, as shown below.

17. Click the “Start” button next to the “Apache” module. If both the PID(s) and Port(s) are filled in with values (similar to the following), the Apache server is now up and running.

18. If you encounter the “Port 80 (or 443) in use” issue, skip to Appendix A for the solution.

No value assigned Port 80 or 443 in use 12:51:22 PM [Apache] Problem detected! 12:51:22 PM [Apache] Port 80 in use by "Unable to open process" with PID 4! 12:51:22 PM [Apache] Apache WILL NOT start without the configured ports free! 12:51:22 PM [Apache] You need to uninstall/disable/reconfigure the blocking application 12:51:22 PM [Apache] or reconfigure Apache and the Control Panel to listen on a different port

19. Click the “Start” button next to the “MySQL” module. If both the PID(s) and Port(s) are filled in with values (similar to the following), the MySQL server is now up and running.

26

20. If you encounter the “Port 3306 in use” issue, skip to Appendix B for the solution.

No value assigned Port 3306 in use 23:02:03 [mysql] Problem detected! 23:02:03 [mysql] Port 3306 in use by ""C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --defaults-file="C:\Program Files\MySQL\MySQL Server 5.1\my.ini" MySQL"! 23:02:03 [mysql] MySQL WILL NOT start without the configured ports free! 23:02:03 [mysql] You need to uninstall/disable/reconfigure the blocking application 23:02:03 [mysql] or reconfigure MySQL and the Control Panel to listen on a different port 23:02:03 [mysql] Attempting to start MySQL service...

21. If the “Windows Security Alert” windows, as shown below, pops up, simply click “Allow Access”.

22. With the Apache server running, use a browser to go to http://localhost, the following should now displays.

23. With MySQL server running, open a Command Prompt.

24. In the prompt, type x: and press Enter, where “x” is the drive name of the USB drive. The following use “F” as example.

C:\Users\user>f: F:\>

25. Type notepad sql.bat and press [Enter] to use Notepad to create new “batch” file named “sql.bat”. Click Yes to confirm.

27

F:\>notepad sql.bat

26. Type in the following content to Notepad.

@echo off path=%path%;%CD%xampp\mysql\bin; mysql -u root -p

27. Save and exit the sql.bat file.

28. Type sql.bat and press [Enter] to runt the sql.bat file.

F:\>sql.bat

29. When being prompted to enter the password, simply press [Enter]. The “MariaDB [(none)]>” prompt should now appear.

Enter password: Welcome to the MariaDB monitor. Command end with ; or \g. Your MariaDB connection id is 2 Server version: 10.1.10-MariaDB mariadb.org binary distribution ...... MariaDB [(none)]>

30. Close the Command Prompt.

31. Click the “Stop” button next to “Apache” and “MySQL” servers.

32. Close the “XAMPP Control Panel”.

33. Be sure to unplug the USB drive. As of now, XAMPP has been successfully installed in the USB drive to support all learning activities for this course.

Preparation #2: Refreshing the settings 1. Plug in the USB flash drive and record the drive name: ______. [Note: Each time when plugging the USB flash drive, the system might assign a different drive name. Do not assume any default.]

2. Close all the applications that may cause conflicts with XAMPP such as Skype, IIS, Wampserver, VMware, etc.

3. Use Windows Explorer to find the “X:\xampp\setup_xampp.bat” file (where “X” is the drive name such as “F”), and the double click it to launch the program. One of the following messages will be displayed in the popped-up Command Prompt.

Situation 1 Situation 2 Sorry, but ... nothing to do! Do you want to refresh the XAMPP installation? 1) Refresh now! Press any key to continue . . . x) Exit

4. If encountering the “Situation 2”, simply press 1 and press [Enter] to refresh (reconfiguring) settings to match with the new drive name (if necessary). After the re-configuration succeeds, the following message will appear.

28

XAMPP is refreshing now... Refreshing all paths in config files... Configure XAMPP with awk for ‘Windows_NT’ ###### Have fun with ApacheFriends XAMPP! ###### Press any key to continue ...

5. Press any key to close the command prompt.

6. Double click the “X:\xampp\xampp-control.exe” file (replace “X” with the drive name) to launch the “XAMPP Control Panel”, and then start Apache.

Preparation #3: 1. Insert the USB flash drive to the computer. Record the drive name: ______. (e.g. “F”).

2. Open a Command Prompt.

3. Type x: and press [Enter] (be sure to replace “x” with the correct drive name). The following use “F” as example.

C:\users\User>e: F:\>

4. Type notepad perl.bat and press [Enter] to use Notepad to create a batch file named “perl.bat”.

F:\>notepad perl.bat

5. In the Notepad editor, type the following code.

@echo off path=%path%;%CD%xampp\perl\bin;

6. Save and exit the file. You should now return to the prompt.

7. In the prompt, type perl.bat and press [Enter].

F:\>perl.bat

8. In the prompt, type cd X:\xampp\htdocs and press [Enter] (be sure to replace “X” with the correct drive name) to change to the “X:\xampp\htdocs” directory.

F:\>cd X:\xampp\htdocs F:\xampp\htdocs>

9. In the “x:\xampp\htdocs” directory, type md myperl and press [Enter] to create a new directory named “myperl” and the path should be “x:\xampp\htdocs\myperl”.

29 F:\xampp\htdocs>md myperl

10. Type cd myperl and press [Enter] to change to the “myperl” directory.

F:\xampp\htdocs>cd myperl F:\xampp\htdocs\myperl>

11. In the “myperl” directory, type notepad lab0_1.pl and press [Enter] to use Notepad to create a new script file named “lab0_1.pl”. Type in the following code. Be sure to replace “X” with the correct drive name.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n"; print "Hello, CIS245!";

12. Save and exit the script file.

13. In the prompt, type perl –c lab0_1.pl and press [Enter] to check syntax of the script. If no error, you should get the following:

F:\xampp\htdocs\myperl>perl –c lab0_1.pl lab0_1.pl syntax ok

14. Type perl lab0_1.pl and press [Enter] to run the script. You should get:

F:\xampp\htdocs\myperl>perl lab0_1.pl Content-Type: text/html

Hello, CIS245!

Learning Activity #1: Your First Perl Script 1. Insert the USB flash drive to the computer. Record the drive name: _____.

2. Start the Apache server using XAMPP Control Panel.

3. Locate the “X:\xampp\htdocs” directory (where X: is the USB thumb drive or hard drive) and create a new subdirectory named “myperl”. Make sure the path is X:\xampp\htdocs\myperl, and be sure to replace X with the correct drive name.

4. In the “X:\xampp\htdocs\myperl” directory, use any generic text editor, such as Windows Notepad, to create a file named lab1_1.pl with the following content. Be sure to replac “X” with the correct drive name.

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print ""; print "\n"; print "

Welcome to my first Perl code!

\n"; print "";

30

5. Use Web browser to visit http://localhost/myperl/lab1_1.pl (where “localhost” is your computer), you should see the following window. Notice that you need to use http://localhost:81/myperl/lab1_1.pl if you modified the port number from 80 to 81 (as specified in Appendix A).

Figure 1

6. In the tool bar of Web browser, click “View” and then “Source” to view the source code generated by the above Perl script. It should looks:

Welcome to my first Perl code!

7. Download the “assignment template”, and rename it to lab1.doc if necessary. Capture a screen shot similar to the above Figure 1 and paste it to a Word document named lab1.doc (or lab1.docx or .pdf).

8. Open a Command Prompt.

9. In the prompt, type cd X:\xampp\htdocs\myperl and press [Enter] to change to the “myperl” directory.

10. Type perl lab1_1.pl and press [Enter] to execute the script in the command-line interface. A sample output looks:

Content-Type: text/html

Welcome to my first Perl code!

Learning Activity #2: Testing CGI.pm configuration 1. In the “X:\xampp\htdocs\myperl” directory, use Notepad to create a new Perl script file named lab1_2.pl with the following contents:

#!"X:\xampp\perl\bin\perl.exe" use strict; use CGI; my $q = new CGI;

print $q->header("text/html"); print $q->start_html("Hello"); print $q->h2("Hello CIS245!"); print $q->end_html;

2. Test the program with Web browser. A sample output looks:

31

3. Use the browser’s “View Source” or “Source” function to view the source code. It should look similar to:

Hello

Hello CIS245!

4. Capture a screen shot similar to the above figure and paste it to a Word document named lab1.doc (or lab1.docx or .pdf).

Learning Activity #3: Debugging 1. In the “X:\xampp\htdocs\myperl” directory, use Notepad to create a new script file named lab1_3.pl with the following lines:

#!"X:\xampp\perl\bin\perl.exe"

print "\n"; print "Test Page\n"; print "Hello World!\n" print "\n";

2. Open a Command Prompt, and change to the “myperl” directory.

3. In the prompt, type perl –c lab1_3.pl and press [Enter] to check the syntax.

E:\xampp>htdocs\myperl>perl -c lab1_3.pl syntax error at lab1_3.pl line 6, near "print" lab1_3.pl had compliation errors.

4. Test the program using Web browser. A sample error message looks similar to the following.

5. Modify the source code by adding the missing semicolon sign (;):

#!"X:\xampp\perl\bin\perl.exe"

print "\n";

32 print "Test Page\n"; print "Hello World!\n"; print "\n"; add the missing ;

6. In the Command Prompt, check the syntax again. It should now say:

lab1_3.pl syntax OK

7. Test the code with a web browser again. The following “Server error” message appear. (How could it be possible when there is no syntax error? The error is caused by MIME, not Perl)

...... Error message: malformed header from script 'lab1_3.pl': Bad header: ......

8. Modify the source code by adding the missing (MIME Content-Type) line:

#!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n";

print "\n"; print "Lab 1-4\n"; print "\n"; print "Hello World!\n"; print "\n";

9. Test the script over Internet again, you should now see:

10. Capture a screen shot similar to the above figure and paste it to a Word document named lab1.doc (or lab1.docx or .pdf).

Learning Activity #4:

1. In the “X:\xampp\htdocs\myperl” directory, use Notepad to create a new script file named lab1_4.pl with the following lines. However, this script contains some syntax errors. Analyze this script, debug it, and make it a functional complete code:

#!"X:\xampp\perl\bin\perl.exe"

print ""; print Lab 1-4"; print "\n print An apple a day keeps doctors away.
"; print "An onion a day keeps everybody away.\n" print "
Perl is fun!";

2. Test the program with Web browser. A sample output looks:

33

3. Find the errors and fix them so the output will eventually looks:

4. Capture a screen shot similar to the above figure and paste it to a Word document named lab1.doc (or lab1.docx or .pdf).

Learning Activity #5: 1. In the “X:\xampp\htdocs\myperl” directory, use Notepad to create a new script file named lab1_5.pl that outputs the following HTML document. Change YourFullName to your full name.

#!"X:\xampp\perl\bin\perl.exe" ## File Name: lab1_5.pl ## Student: YourFullNameHere print "Content-Type: text/html\n\n";

print ""; print "Lab 1-5"; print ""; print "Frults:

    "; print "
  • Apple
  • "; print "
  • Orange
  • "; print "
  • Banana
  • "; print "
"; print "";

2. Test the program with Web browser. A sample output looks:

3. Capture a screen shot similar to the above figure and paste it to a Word document named lab1.doc (or lab1.docx or .pdf).

Submittal 1. Complete all the 5 learning activities in this lab. 2. Create a .zip (not .rar or other format) file named lab1.zip containing ONLY the following script files.

34 • lab1_1.pl • lab1_2.pl • lab1_3.pl • lab1_4.pl • lab1_5.pl • lab1.doc (or lab1.docx or .pdf) [You may be given zero point if this Word document is missing]

3. Upload the zipped file to Question 11 of Assignment 1 as the response.

Programming Exercise #01 1. Use Notepad to create a new file named “ex01.pl” with the following lines in it (be sure to replace YourFullNameHere with the correct one):

#!"X:\xampp\perl\bin\perl.exe" ## File name: ex01.pl ## Student: YourFullNameHere

2. Next to the above two lines, write Perl code that will: (a) use

tags to enclose your full name; (b) use the localtime() function to retrieve the current date and time values from the server; and (c) display the result in a web browser similar to the following.

3. Download the “programming exercise template”, and rename it to ex01.doc. Capture a screen shot similar to the above figure and paste it to a Word document named ex01.doc (or .docx or .pdf).

4. Create a .zip file named ex01.zip with the following two files. Upload the .zip file for grading. • ex01.pl • ex01.doc (or .docx or .pdf) [You may be given zero point if this Word document is missing]

Grading Criteria 1. You code must fully comply with the requirement to earn full credits. No partial credit is given.

Appendix A: “Port 80 (or 443) in use” 1. If it is “Port 80” that was conflicted by other service, in the Control Panel, click the “Config” button next to “Apache”, and then click the “Apache (httpd.conf)” option.

2. Scroll up and down to find the following section.

#Listen 12.34.56.78:80 Listen 80

3. Change 80 to 81.

#Listen 12.34.56.78:80 Listen 81

35

4. Find the following section.

# ServerName localhost:80

5. Change 80 to 81.

# ServerName localhost:81

6. Save and exit the .ini file.

7. If it is “Port 443” that was conflicted by other service, in the Control Panel, click the “Config” button next to “Apache”, and then click the “Apache (httpd-ssl.conf)” option.

8. Scroll up and down to find the following section.

# Listen 443

9. Change 443 to 4499

# Listen 4499

10. Find the following section.

# General setup for the virtual host DocumentRoot "D:/xampp/htdocs" ServerName www.example.com:443 ServerAdmin [email protected]

11. Change both 443 to 4499.

# General setup for the virtual host DocumentRoot "D:/xampp/htdocs" ServerName www.example.com:4499 ServerAdmin [email protected]

12. Restart the Apache server by clicking the “Start” button. If Apache starts and runs smoothly, return to Preparation #1. By the way, be sure to the URL: “http://localhost:81/” to access localhost.

Appendix B: “Port 3306 in use” 1. In the Control Panel, click the “Config” button next to “MySQL”.

36 2. Scroll up and down to find the following section.

# The following options will be passed to all MySQL clients [client] # password = your_password port = 3306 socket = "F:/xampp/mysql/mysql.sock"

3. Change 3306 to 3307.

# The following options will be passed to all MySQL clients [client] # password = your_password port = 3307 socket = "F:/xampp/mysql/mysql.sock"

4. Save and exit the .ini file.

5. Start the MySQL server by clicking the “Start” button. If Apache starts and runs smoothly, return to Preparation #1.

37