Lecture #2 Syntaxes

Introduction A Perl script consists of a sequence of declarations and statements which run from the top to the bottom; therefore, the scripting requires basic understanding of syntaxes. Literally, a declaration specifies the name and data type of a variable or script element; statements are the instructions programmers write to tell Perl interpreter what to do. The following is a declaration of variable x as scalar type of data. In programming, any data types that hold a single data item called scalar (or base) data types. Programming languages like ++ or Java has scalar type like char, int, short long, float, and double. Interestingly, Perl does not have a variety of scalar data types. Perl only distinguish string and numbers.

$x = 7; # variable

The following is a sample statement. Perl statements end in a semi-colon (;):

print "Hello, world!";

Statements frequently contain expressions. An expression is something which evaluates to a value. The following is a statement with an expression because (3<5) will be evaluated to true. The ouput is 1 which means true.

print (3<5);

Expressions are often part of a loop (repetition structure) or a decisive statement (such as the if statement or the conditional operator) because they typically return a Boolean result: true or false. The following uses the conditional operator (? :) to evaluate an expression ($s > 60).

#!"X:\xampp\perl\bin\perl.exe" print "Enter your score: ";

$s = <>; $grade = ($s > 60)? "passed" : "Not passed"; print "$grade\n";

A Perl script is made of a combination of statements. Some statements are declaration; others are expressions. Many statements contains both declaration and expressions. The following is an example of complicated Perl statements.

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

print "", # comma as separator "Test Page", #comma as separator ""; # semicolon [end of line]

$x = 7; # declare a scalr variable $y = 5; # variable

if ($y <= $x) # test expression { $msg = "CIS245!"; # variable }

print "$msg";

38 All the lines of code you have just seen are examples of Perl statements. Basically, a statement is one task for the Perl interpreter to perform. A statement can contain construct, variables, expression, or any combination of them. The semicolon (;) indicates the end of each statement, while comma (,) is a separator between sections of a statement. The print construct, as discussed in the previous lecture, supports the comma (,) sign to break a long statement into lines.

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

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

Hello, World!

", "";

A Perl program can be thought of as a collection of statements performed one at a time. When the Perl interpreter sees a statement, it breaks the statement down into smaller units of information. In this example, the smaller units of information are $x, =, 7, and ;. Each of these smaller units of information is called a token.

Perl statements can be grouped into blocks. A Perl block is enclosed by a pair of curly brackets. In the above code, the if statement is an example of blocks. The following is another example that uses the “sub” keyword to create a subroutine which has its own code block. A later lecture will discuss to how create subroutine in details.

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

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

print ""; print "";

sub Hello { print "Hello, World!"; }

Hello(); #call the subroutine

print "";

Perl is a case sensitive language. File names, variables, and arrays are all case sensitive. If you capitalize a variable name when you define it, you must capitalize it to call it. $X and $x are two different variables.

Perl Data Perl has three built-in data types: scalars, arrays, and hashes. A scalar is either a single string Types and or a number in most of the cases. Yet, it can also be a reference to something. A sting literal is Variables a combination of characters enclosed by either single quotes or double-quotes. These quotes are not a part of the string they just mark the beginning and end of the string for the Perl interpreter. The following are some examples.

'239' "45.5" 'four' "Jennifer Lopez" "Penn State University"

Both ‘239’ and “45.5” are not numbers. ‘239’ is not a unit of anything. It is a combination of : 2, 3, and 9. “45.5” does not mean a value of forty-five and a half. It is a combination

39 of characters: 4, 5, ., and 5. The blank space between Jennifer and Lopez in the string “Jennifer Lopez” as well as those in “Penn State University” is also a character called “blank” character.

There are actually two varieties of null strings (sometimes referred to as “empty” strings), a defined one and an undefined one. The defined version is just a string of length zero, such as "" .

#!"X:\xampp\perl\bin\perl.exe" $x = ""; print $x;

The undefined version is the use of keyword “undef” which indicates “no real value” for the variable.

#!"X:\xampp\perl\bin\perl.exe" $x = undef; print $x;

It is necessary to understand the difference between a and a blank character. A null character does not take any bits, while a blank character does. A blank character can be considered as an invisible character. The following is a sample code that use the length() method to return the length of characters in a string. The comma sign (,) is the separator of the print function, and “\n” inserts a .

#!"X:\xampp\perl\bin\perl.exe" print length(""), "\n
"; print length(" "), "\n
"; print length(''), "\n
"; print length(' '), "\n
";

To test the above code, name the script as “test.pl” and save it under the “X:\xampp\perl\bin\” directory, where “X” is the drive name that host XAMPP. Open the Microsoft Command Prompt, change to the “X:\xampp\perl\bin\” directory, and then issue perl test.pl.

X:\cd xampp\perl\bin X:\xampp\perl\bin>pel test.pl 0 1 0 1

Numeric literals (numbers) could be floating point or integer formats, as shown in the following table.

Format Example integer 627 floating point 345.29 Scientific .23E-10 hex 0xff octal 0377 binary 0b011011

The following is a Web-ready script that illustrates how these variations works. Interestingly, most Web browser ignores blank space created by “\n”. To break a line in a browser, you need to use the
HTML tag.

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

40 print ""; print "";

print 627, "\n
"; print 345.29, "\n
"; print .23E-10, "\n
"; print 0xff, "\n
"; print 0377, "\n
"; print 0b011011, "\n
";

print "";

It is necessary to distinguish string and numbers.  Strings may contain any symbol, letter, or number. Must be enclosed by quotes. E.g. “23”, “3.1412”, and “hell”.  Numbers may contain exponents, integers, or decimal values. E.g.: 23, 3.1412.

A Perl variable is a temporary name given by the programmers to mark an area of the physical memory to temporarily store a value. Throughout the duration of the Perl script. In Perl, variables are declared to hold a scalar which could be a single value, such as a string, a number, or a reference. A Perl variable names begin with a dollar sign ($). They can be any combination of letters, numbers, or underscores. Names that start with a digit may only contain more digits. Names that do not start with a letter, digit, or underscore are limited to one character besides the $ ($*, etc.).

$x $age $firstName $Student_ID $bloodType

Perl variables do not have to be explicitly declared to reserve memory space, which means you do not need to specify the data type like int, float, double, string, char, and so on. The following compare Perl variable declaration with that in C++.

Perl C++ $x double x $age float age $firstName string firstName $Student_ID string Student_ID $bloodType char bloodType

The above scalar variables (age, firstName, and Student_ID) do not have initial values (also known as default values), meaning they do not represent any value at the time they are declared. Perl uses assignment statements to give a variable some value, or to change the existing value of a variable. The following is the syntax for assigning a value to a variable, where variableName is the variable’s name, and value is the number or string you want to store in (or be represented by) the variable name.

variableName = value;

The following is a script that demonstrates how to declare variables and assign their initial values. Again, when declaring a string variable with initial value, the value must be enclosed by a pair of quotes.

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

print "";

41 print "";

$x = 3.12; $age = 41; $firstName = "Jennifer"; $Student_ID = "D004821256"; $bloodType = 'A'; $score = "";

print "";

The syntax to retrieve the value of a variable is:

$variableName

The following is an Web-ready script that illustrates how to declare a variable, assign an initial value, and retrieve the value of a Perl variable.

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

print ""; print "";

$x = 3.12; $age = 41; $firstName = "Jennifer"; $Student_ID = "D004821256"; $bloodType = 'A'; $score = "";

print $x, "\n
"; print $age, "\n
"; print $firstName, "\n
"; print $Student_ID, "\n
"; print $bloodType, "\n
";

print "";

Remember, a scalar variable can only hold one value at a given time. Null value (means nothing) is also considered a value. You can assign a null value using “” or ‘’. For example:

$score = ""; $sale_amount='';

The following is another example that show how to combine the value held by a particular variable with other strings using the print function.

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

print ""; print "";

$animal = "camel"; $answer = 42; $weight = 183.57;

print "There are $answer $animal!\n
The square of $weight is ", $weight * $weight, "!";

print "";

42

A sample output looks:

A short-hand way to declare two or more variables with initial values is to place them in parentheses with sequences, as shown below.

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

($a, $b) = (2, 4); print $a, "\n
"; print $b, "\n
";

($x, $y, $z) = (5, 7, 9);

print $x, "\n
"; print $y, "\n
"; print $z, "\n
";

print "";

The statement, ($a, $b) = (2, 4);, actually equals to the following statements.

$a = 2; $b = 4;

Unlike variables, constants are values that stay the same throughout the entire life spam of Perl applications. Creating a constant in Perl requires the use of “constant” module with the following syntax, where use is a directive and constant is a keyword.

use constant constantName => value;

The following depicts how to declare a constant in Perl. The constant name is “PI” and its value is 3.14195. The script then uses the circumference formula, 2πr, to find the circumference. Perl constants do not have to prefix by a $ sign.

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

use constant PI => 3.14195;

print "Enter the radius: "; $r = <>; print "Circumference is ", 2 * PI * $r;

When you declare a constant such as PI using the method shown above, each machine your script runs upon can have as many digits of accuracy as it can use. Also, your program will be easier to read, more likely to be maintained (and maintained correctly), and far less likely to send a space probe to the wrong planet because nobody noticed the one equation in which you wrote 3.14195 .

43 Instead of writing multiple “use constant” statements, you may define multiple constants in a single statement by giving, instead of the constant name, a reference to a hash where the keys are the names of the constants to be defined. To declare multiple constant in Perl, simply place the constantName => value set within the curly brackets { }, as shown below.

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

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

print ""; print "";

use constant { SEC => 0, MIN => 0, HOUR => 0, MDAY => 1, MON => 0, YEAR => 2025, };

print "2025 New Year Day
"; print MDAY, "/", (MON+1), "/", YEAR, " ", HOUR, ":", MIN, ":", SEC;

print "";

Interestingly, Perl does not have a special boolean type. Yet, Perl can evaluate Boolean expression and return 1 for true and 0 for false. The following is how the instructor go around this limit. Both “true” and “false” are names of constants. Their values are 1 and 0 respectively.

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

use constant true => 1; use constant false => 0;

if (3>5) { print true; } else { print false; }

The following is another version. It defines two constants in a single statement.

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

use constant { false => 0, true => 1 };

if (3>5) { print true; } else { print false; }

A Perl array is a variable that stores an ordered list of scalar values. Array variables are preceded by an “at” (@) sign. The following creates an integer array named “x”.

@x = (25, 30, 40, 45);

The following creates a string array named “major”.

@major = ("CIS", "MIS", "IST");

44

The following is the syntax to retrieve an element of a Perl array, where i is the index of the element.

$arrayName[i]

The following is a Web-ready code that illustrates how to create Perl arrays and retrieve their values.

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

print ""; print "";

@x = (25, 30, 40, 45); @major = ("CIS", "MIS", "IST");

print $x[2], "\n
"; print $major[0];

print "";

A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. A hash is similar to an array except that they link a key to a value. A Perl hash must be created using the following syntax, where a “key” is a scalar that can identify a scalar value.

%hashName = ( key1, value1, key2, value2, ...... keyn, valuen, );

In the following hash, “state” is the name of the hash. “CA”, “WA”, and “PA” are keys of “California”, “Washington”, and “Pennsylvania”.

%state = ("CA", "California", "WA", "Washington", "PA", "Pennsylvania");

As a matter of fact, there is no need to break the line.

%state = ("CA", "California", "WA", "Washington", "PA", "Pennsylvania");

The syntax to retrieve an element is:

$hashName{key}

The following is a Web-ready script that illustrates how to implement a Perl hash.

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

print ""; print "";

%state = ("CA", "California", "WA", "Washington", "PA", "Pennsylvania");

45 print $state{PA}, "\n
";

print "";

Perl arrays and hashes will be discussed in detailas in a later lecture.

There are some variables which have a predefined and special meaning in Perl. They are the variables that use punctuation characters after the usual variable indicator ($, @, or %), such as $_, which is said to be the “default variable” and it contains the default input and pattern- searching string. The following uses a for loop to repeatedly display the very current value of every iteration in the range from 1 to 100. A later lecture will discuss how the for loop work in details.

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

for (1..100) { print $_, "\n"; }

Perl also provides several special literals, such as __FILE__, __LINE__, and __PACKAGE__, which represent the current filename, line number, and package name at that point in the current program. By the way __ is made of by two underscore sign (_).

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

print ""; print "";

print "File name: ". __FILE__ . "\n
"; print "Line Number: " . __LINE__ ."\n
"; print "Package: " . __PACKAGE__ ."\n
";

print "";

The variable $ENV is a special associative array within Perl that holds the contents of your environment variables. The syntax is:

$ENV{'variableName'}

Perl supports the following environment variables through CGI.

Environment Variable Description The revision of the Common Gateway Interface that the server GATEWAY_INTERFACE uses. SERVER_NAME The server's hostname or IP address. The name and version of the server software that is answering SERVER_SOFTWARE the client request. The name and revision of the information protocol the request SERVER_PROTOCOL came in with. SERVER_PORT The port number of the host on which the server is running. REQUEST_METHOD The method with which the information request was issued. PATH_INFO Extra path information passed to a CGI program. The translated version of the path given by the variable PATH_TRANSLATED PATH_INFO. The virtual path (e.g., /cgi-bin/program.pl) of the script being SCRIPT_NAME executed.

46 DOCUMENT_ROOT The directory from which Web documents are served. The query information passed to the program. It is appended to QUERY_STRING the URL with a "?". REMOTE_HOST The remote hostname of the user making the request. REMOTE_ADDR The remote IP address of the user making the request. AUTH_TYPE The authentication method used to validate a user. REMOTE_USER The authenticated name of the user. The user making the request. This variable will only be set if REMOTE_IDENT NCSA IdentityCheck flag is enabled, and the client machine supports the RFC 931 identification scheme (ident daemon). CONTENT_TYPE The MIME type of the query data, such as "text/html". The length of the data (in bytes or the number of characters) CONTENT_LENGTH passed to the CGI program through standard input. The email address of the user making the request. Most HTTP_FROM browsers do not support this variable. HTTP_ACCEPT A list of the MIME types that the client can accept. HTTP_USER_AGENT The browser the client is using to issue the request. The URL of the document that the client points to before HTTP_REFERER accessing the CGI

The following is a complete code that illustrates how to use $ENV variable.

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

print ""; print "";

print "Server Name: ", $ENV{'SERVER_NAME'}, "
\n"; print "Running on Port: ", $ENV{'SERVER_PORT'}, "
\n"; print "Server Software: ", $ENV{'SERVER_SOFTWARE'}, "
\n"; print "Server Protocol: ", $ENV{'SERVER_PROTOCOL'}, "
\n"; print "CGI Revision: ", $ENV{'GATEWAY_INTERFACE'}, "
\n";

print "";

Throughout this course, you will use the following to find the file name of the script.

$ENV{SCRIPT_NAME}

The following is a complete Perl script that uses the $ENV environment variable to post user entry to the script file itself. A later lecture will discuss how the HTML form works.

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

use CGI qw(:standard);

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

print ""; print "";

if (param) { $fn = param("fn"); print "Welcome, $fn!"; }

else

47 { print "

"; print "Enter your full name: "; print ""; print "
";

}

print "";

Perl In Perl, the # (pound sign or sharp sign) to indicate the beginning of one-line comments. Any Comments words, spaces, or marks after a pound sign will be ignored by the Perl interpreter. The following uses the # sign to write comments.

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

######################################### # Student: Jennifer Lopez # #########################################

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

print ""; print "";

print "My name is Nicole Kidman."; # display Nicole Kidman

print "";

Here is another example. Its second line is completely ignored by Perl interpreter, because it starts with a # sign.

#!"X:\xampp\perl\bin\perl.exe" # display a message print "Hi, Perl!";

Adding multi-line comments in Perl is done by using the “=” sign. Lines starting with “=” are interpreted as the start of a section of embedded documentation (pod), and all subsequent lines until the ending “=cut” are ignored by the compiler. The following example demonstrates how it works.

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

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

print ""; print "";

print "My name is Nicole Kidman.";

=Multiline comment This is the first line. This is the second line. This is the third line. =cut

print "";

Quotation When working with strings in Perl, there is a difference between single (‘) and double (“) Marks May quotation marks. If you surround a string with single quote marks, Perl will use the string Matter directly, without substituting the variable definitions first.

48

#!"X:\xampp\perl\bin\perl.exe" $str = "apple"; print '$str';

The output is:

$str

If you use double quote marks, Perl will replace the variable’s name with its value (a process known as interpolation) before using the string.

#!"X:\xampp\perl\bin\perl.exe" $str = "apple"; print "$str";

The output is:

apple

Apparently, when using single quotes (') for strings, all characters are printed as-is. When using double quotes (“) for strings, whatever is supposed to function will function normally. The following is another Web-ready example.

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

print "";

$name1="Jennifer Lopez"; $name2="Lea Thompson";

print "$name1", "
"; print '$name2', "
";

print "";

The output on a browser looks like this:

Jennifer Lopez $name2

In the Command Prompt, the output looks:

Content-Type: text/html

Jennifer Lopez
$name2

Consider the following two cases. The first one declares only one variable “$user”, assigns an initial value “student” to it, and then use the “print” method to combine three separated strings as one single string message. Consequently, the word “student” (which is held by the $user variable) and a letter “s” is closely combined to make a “students” word.

## $user is the name of variable $user = "student"; print "These " , $user , "s are good kids.";

49

## $user and $users are two variables $user = "student"; $users = "monsters"; print "These $users are good kids.";

In the second example, “$user” and “$users” are two different variables, and each has an initial value. Interestingly, “$user” will be considered as a combination of characters if you choose to use single quote.

$user = "student"; print 'These $users are good kids.';

Quotation marks are fairly ubiquitous in Perl. Be sure to learn the different between single and double quotes.

Escape Perl supports “escape characters”. Character combinations consisting of a (\),such as Sequence “\n”, followed by a letter or by a combination of digits are called “escape sequences.” To represent a newline character, single quotation mark, or certain other characters in a character constant, programmers must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant. Perl’s escape characters all have the backslash (\) character that is used to form escape sequences. The following table lists commonly used sequence escapes.

Sequence Description \t add a tab \n start a new line ("Enter") \b force a backspace \a alarm sound \u set the character that follows to uppercase \U set all the characters that follow to uppercase \l set the character that follows to lowercase \L set all of characters that follow to lowercase

The following uses “\a” to play few alarm sounds in the command-line.

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

print "\a\a\a\a\a";

For example:

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

print "Content-Type: text/html\n"; print "\n\n", "\tTest Page\n\n\n", "\U\n\n";

print "\U";

50

In a Command Prompt, the output looks similar to the following (the gray area represent the tab). Ironically, most Web browsers ignore tabs and blank spaces. In other words, “\t” and “\n” have no effect on Web contents.

Content-Type: text/html

Test Page

You have create several sample Perl scripts with the , “\n”, which denotes a newline (also known as a line break or end-of-line character) to insert a new line in the console screen (Command Prompt or Shell Prompt for Linux). The statement print "Content- Type: text/html\n"; actually produces the following results in a console screen. The gray line represent one blank line.

Content-Type: text/html

Interestingly, “\n” is ignored by the web browser. Therefore, the blank line generated by “\n” will not appear on the browser’s content area. In the following example, “\n” will insert a new line. That’s being said the output should have to two lines.

#!"X:\xampp\perl\bin\perl.exe" print "Line 1\nLine 2";

The results in a console screen is:

Line 1 Line 2

However, in a Web browser, the result becomes:

Line 1Line 2

Why did not \n work? The newline, \n, is not an HTML tag and is not recognizable to the Web browser (because browsers are designed to read HTML tags). The
HTML tag is the line breaker tag, and is the one the browser accepts as instruction to insert a new line. If you wish to use Perl script to generate HTML output, then the correct way to write the code is:

#!"X:\xampp\perl\bin\perl.exe" print "Line1\n
Line2";

Many Perl code samples used in later lecture will contain the “\n
” combination. The “\n” part is for Perl interpreter, while “
” is for browser to read.

Unfortunately there is no TAB tag available in html. The instructor use HTML’s blank space code “ ” to go around this limits.

For example:

print "\t     A tabbed line";

51

Making the Perl by default is a loosely design langauge. In order to make Perl script more rigid and robust, script safer the official Perl document recommends programmer to start every program with one the following lines or both. By the way, “use” is a keyword while “strict” and “warnings” are named of Perl modules.

use strict; use warnings;

These two lines forces the Perl intepreter to rigidly check the script in order to catch various common problems. The “strict” module is a Perl pragma to restrict unsafe constructs. It is a module to provide safest mode to operate Perl scripts, but it is sometimes too strict for casual programming. The warnings module is a replacement for the command line flag “-w”. A potential problem caught by “strict” will cause your code to stop immediately when it is encountered, while a problem caught by “warnings” will merely cause a warning message and the script can still run.

When using the Perl’s “strict” module (as you will experience in later lectures), you have to declare variables using the “my” keyword the first time you declare them. This is a requirement of the strict module, but Perl. For example, to declare a variable named animal with an initial value camel, use:

my $animal = "camel";

A previous section demonstrates how you declare variable without using this “my” keyword, therefore, you may have an impression that the “my” keyword is redundant. In reality, the “my” keyword denotes that this $animal variable belongs to a particular scope.

Without “strict” With “strict” #!"X:\xampp\perl\bin\perl.exe" #!"X:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n"; use strict;

print ""; print ""; print ""; print "Content-Type: text/html\n\n"; $name1="Jennifer Lopez"; $name2="Lea Thompson"; print "";

print "$name1", "
"; my $name1="Jennifer Lopez"; print '$name2', "
"; my $name2="Lea Thompson";

print ""; print "$name1", "
"; print '$name2', "
";

print "";

It is necessary to understand the concept of scope in Perl, with and without the use of the “strict” module. In the following example, the variable $i is not restricted by any scope. Although $i is declared inside the for structure, it can be accessed by the print function which is outside the for structure (due to no restriction). A later lecture will discuss the for structure in details.

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

for ($i=0; $i<=5; $i++) { $i; }

52

print $i; # display 6

In the following example, the $i variable is limited to the “for” loop which is the scope. The “my” keyword declares the $i variable to be valid only within the scope. The print function is outside the scope and thus cannot access the $i variable.

#!"X:\xampp\perl\bin\perl.exe" use strict;

for (my $i=0; $i<=5; $i++) { $i; }

print $i; # display error

This is a access-control issue. The “strict” module will force the interpreter to terminate the execution and display the following error message.

Gloabl symbol "$i" requires explicit package name at test.pl line 10. Execution of test.pl aborted due to the compilation errors.

The following script illustrates the correct way to declare $i as a global variable with the “my” keyword.

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

use strict;

my $i;

for ($i=0; $i<=5; $i++) { $i; }

print $i;

Apparently, without using the “strict” module and the “my” keyword, a variable is considered global. In the following example, $x is treated as a global variable of the entire script even though it is declared inside the for loop.

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

for ($i=0; $i<=5; $i++) { $i; $x = $x + $i; }

print $x;

The “my” keyword creates lexically scoped variables instead. The variables are scoped to the block (i.e., a bunch of statements surrounded by curly-braces) in which they are defined.

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

print "";

53 print "";

my $x = "foo"; my $i = 1;

if ($i) { my $y = "bar"; print $x; # prints "foo" print $y; # prints "bar" }

print $x; # prints "foo" print $y; # prints nothing; $y has fallen out of scope

print "";

Review 1. Given the following code segment, which is a small unit of information called a token? Questions $x = 7;

A. $x B. = C. 7 D. All of the above

2. Which declare a Perl constant named “apple” with a value “fruit”? A. use constant { apple = fruit }; B. use constant apple => fruit; C. use constant apple = fruit; D. use constant apple -> fruit;

3. Which yields exactly the same output as the following does in Perl?

print "Hello";

A. echo "Hello"; B. show "Hello"; C. print("Hello"); D. echo("Hello");

4. Given the following program. Why does the "\n" part work when you display the output using a web browser?

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

A. white space is ignored by web browser. B. "\n" should be "\\n" due to the need to escape sequence. C. "\n" should be "/n" due to HTTP format. D. Microsoft hates Perl

5. Which is NOT an example of scalar literal? A. 3.1412 B. apple C. ["cis245", "cis246", "cis247"] D. All of the above

54 6. Given the following program, the output is __.

#!"X:\xampp\perl\bin\perl.exe" $str = "math"; print $str;

A. $str B. "math" C. math D. str

7. Given the following program, the output is __.

#!"X:\xampp\perl\bin\perl.exe" $str = "cis245"; print "$str";

A. str B. $str C. cis245 D. "cis245"

8. Given the following program, the output is __.

#!"X:\xampp\perl\bin\perl.exe" $str = ’cis245’; print ’$str’;

A. str B. $str C. cis245 D. "cis245"

9. Which is equivalent to the following statements?

$x = 1; $y = 3; $z = 5;

A. {$x, $y, $z} = {1, 3, 5}; B. [$x, $y, $z] = [1, 3, 5]; C. ($x, $y, $z) = (1, 3, 5); D. $x, $y, $z = 1, 3, 5;

10. Given the following program, the output is __.

#!"X:\xampp\perl\bin\perl.exe" for ($i=0; $i<=5; $i++) { $i; }

print $i;

A. 0 B. 5 C. 6 D. nothing

55

Lab #2 Perl Programming Basics

Preparation #1: Running the server and create default database 1. Insert the USB flash drive. Record the drive name: ______.

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

3. Insert the USB that contains XAMPP. Determine the drive name (such as “F:\”).

4. Change to the “X:\xampp\” directory (where X must be the correct drive name) to find the “setup_xampp.bat” and then execute it. You should see:

###################################################################### # ApacheFriends XAMPP setup win32 Version # #------# # Copyright (C) 2002-2011 Apachefriends 1.7.7 # #------# # Authors: Kay Vogelgesang ([email protected]) # # Carsten Wiedmann ([email protected]) # ######################################################################

5. Read the option below the above lines. You should see one of the following:

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

6. If you got the “Sorry, but ...” option, skip to the next step to launch Apache with XAMPP Control Panel; otherwise, press 1 and then [Enter]. If re-configuration succeeds, you should see the following message.

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 ...

7. In the “X:\xampp\” directory, click the “xampp-control.exe” file to launch XAMPP control panel.

8. Click the “Start” button next to Apache to start the Apache server.

Learning Activity #1:

56 1. In the “X:\xampp\htdocs\myperl” directory, use Notepad to create a new script file named lab2_1.pl with the following lines. Be sure to replace “X” with the correct drive name, and replace YourNameHere with your full name.

#!"X:\xampp\perl\bin\perl.exe" ####################################### # Student Name: YourNameHere #######################################

print "Content-Type: text/html\n\n"; \n insert a new line

print ""; print "";

print "

This is heading 1.

", # comma "

This is heading 2.

", "

This is heading 3.

", "

This is heading 4.

", "
This is heading 5.
", "
This is heading 6.
";

print length(""), "\n
"; print length(" "), "\n
"; print length(''), "\n
"; print length(' '), "\n
";

print 627, "\n
"; print 345.29, "\n
"; print .23E-10, "\n
"; print 0xff, "\n
"; print 0377, "\n
"; print 0b011011, "\n
";

$x = 3.12; $age = 41; $firstName = "Jennifer"; $Student_ID = "D004821256"; $bloodType = 'A'; $score = "";

print $x, "\n
"; print $age, "\n
"; print $firstName, "\n
"; print $Student_ID, "\n
"; print $bloodType, "\n
";

print "";

2. Use Web browser to visit http://localhost/myperl/lab2_1.pl (where “localhost” is your ), you should see the following window. Notice that you need to use http://localhost:81/myperl/lab2_1.pl if you modified the port number to resolve the port conflicts (as specified in Lab #1). The output looks:

57

3. Download the “assignment template”, and rename it to lab2.doc if necessary. Capture a screen shot similar to the above figure and paste it to a Word document named lab2.doc (or lab2.docx).

4. Open a Command Prompt, type x: and press [Enter] to change to the correct drive. Replace X with the correct drive name.

C:\Users\user>f:

5. Type cd X:\xampp\htdocs\myperl and press [Enter] to change to the “X:\xampp\htdocs\myperl” directory. Replace X with the correct drive name.

6. Type perl lab2_1.pl and press [Enter] to test the result. The output looks:

F:\xampp\htdocs\myperl Content-Type: text/html

This is heading 1.

This is heading 2.

This is heading 3.

This is heading 4.

This is heading 5.
This is heading 6.
0
1
0
1
627
345.29
2.3e-011
255
255
27
3.12
41
Jennifer
D004821256
A

Learning Activity #2:

58 1. In the “X:\xampp\htdocs\myperl” directory, use Notepad to create a new script file named lab2_2.pl with the following lines:

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

print ""; print "";

#variables $animal = "camel"; $answer = 42; $weight = 183.57;

print "There are $answer $animal.\n
The square of $weight is ", $weight * $weight, ".\n
";

#constant use constant PI => 3.14195;

$r = 15;

print "Circumference is ", 2 * PI * $r, ".\n
";

#constants use constant true => 1; use constant false => 0;

if (3>5) { print true, "\n
"; } else { print false, "\n
"; }

use constant { "Speed_of_light" => 2.99792458e8, "Plank_constant" => 6.6260755e-34, "Avogadro_constant" => 6.0221e23, "Faraday_constant" => 96485.309, "Coulomb_constant" => 8.987552e9 };

print Speed_of_light, "\n
"; print Plank_constant, "\n
"; print Avogadro_constant, "\n
"; print Faraday_constant, "\n
"; print Coulomb_constant, "\n
";

print "";

2. Test the program with a web browser. The output is similar to:

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

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

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

print ""; print "";

print "File name: ". __FILE__ . "\n
"; print "Line Number: " . __LINE__ ."\n
"; print "Package: " . __PACKAGE__ ."\n
";

#array @x = (25, 30, 40, 45); @major = ("CIS", "MIS", "IST");

print $x[2], "\n
"; print $major[0], "\n
";

#hash %state = ("CA", "California", "WA", "Washington", "PA", "Pennsylvania");

print $state{PA}, "\n
";

=Multiline comment This is the first line. This is the second line. This is the third line. =cut

#single vs. double quotes $str = "apple"; print '$str', "\n
"; print "$str", "\n
";

$name1="Jennifer Lopez"; $name2="Lea Thompson";

print "$name1", "\n
"; print '$name2', "\n
";

print "\Uthis line must be converted to uppercase.", "\n
"; print "\LTHIS LINE MUST BE CONVERTED TO LOWERCASE.", "\n
";

print "";

2. Test the program with a web browser. The output looks:

60

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

Learning Activity #4: 1. In the “X:\xampp\htdocs\myperl” directory, use Notepad to create a new Perl script file named lab2_4.pl with the following contents:

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

use strict; use warnings;

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

print ""; print "";

my $x = 3.12; my $age = 41; my $firstName = "Jennifer"; my $Student_ID = "D004821256"; my $bloodType = 'A'; my $score = "";

print $x, "\n
"; print $age, "\n
"; print $firstName, "\n
"; print $Student_ID, "\n
"; print $bloodType, "\n
";

my @x = (25, 30, 40, 45); my @major = ("CIS", "MIS", "IST");

print $x[3], "\n
"; print $major[2], "\n
";

my %state = ("CA", "California", "WA", "Washington", "PA", "Pennsylvania");

print $state{CA}, "\n
";

my $str;

for (my $i=0; $i<=5; $i++) { $str .= $i; }

print $str;

print "";

61 2. Test the program with a web browser. The output looks:

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

Learning Activity #5: 1. In the “X:\xampp\htdocs\myperl” directory, use Notepad to create a new Perl script file named lab2_5.pl with the following contents:

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

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

print ""; print "";

use constant { SEC => 0, MIN => 0, HOUR => 0, MDAY => 1, MON => 0, YEAR => 2025, };

print "2025 New Year Day
"; print MDAY, "/", (MON+1), "/", YEAR, " ", HOUR, ":", MIN, ":", SEC, "\n
";

for (1..10) { print $_, " "; }

print "\n
";

($a, $b) = (2, 4); print $a, "\n
"; print $b, "\n
";

($x, $y, $z) = (5, 7, 9);

print $x, "\n
"; print $y, "\n
"; print $z, "\n
";

print "Server Name: ", $ENV{'SERVER_NAME'}, "
\n"; print "Running on Port: ", $ENV{'SERVER_PORT'}, "
\n"; print "Server Software: ", $ENV{'SERVER_SOFTWARE'}, "
\n"; print "Server Protocol: ", $ENV{'SERVER_PROTOCOL'}, "
\n"; print "CGI Revision: ", $ENV{'GATEWAY_INTERFACE'}, "
\n";

print "

The script name is ", $ENV{SCRIPT_NAME};

62

print "";

2. Test the program with a web browser. The output looks:

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

Submittal 1. Complete all the 5 learning activities in this lab. 2. Create a .zip file named lab2.zip containing ONLY the following script files.

 lab2_1.pl  lab2_2.pl  lab2_3.pl  lab2_4.pl  lab2_5.pl  lab2.dox (or lab2.docx) [You may be given zero point if this Word document is missing]

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

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

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

2. Next to the above two lines, write Perl code that will declare three variables: fruit, quantity, and price. Assign initial values according to the following table. Use the “print” method and proper quotation marks to display value of the quantity variable, value of the fruit variable, and value of the price variable in a single string similar to “I bought xx xxxxxs at $x.xx a piece.”

Variable Value fruit orange quantity 12 price 0.47

3. Test the program in a Web browser.

63

4. Download the “programming exercise template”, and rename it to ex02.doc. Capture a screen shot similar to the above figure and paste it to a Word document named ex02.doc (or .docx). 5. Create a .zip file named ex02.zip with the following two files. Upload the .zip file for grading.  ex02.pl  ex02.doc (or .docx) [You may be given zero point if this Word document is missing]

Grading Criteria 1. You will receive zero point if you simply display the message without using these required variables. 2. You code must fully comply with the requirement to earn full credits. No partial credit is given.

64