lecture #2 perl syntaxes declaration statements …students.cypresscollege.edu/cis245/lc02.pdfor a...
TRANSCRIPT
38
Lecture #2 Perl 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 C++ 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"
print "Content-Type: text/html\n\n";
print "<html><head>", # comma as separator
"<title>Test Page</title></head>", #comma as separator
"<body>"; # semicolon [end of line]
$x = 7; # declare a scalr variable
$y = 5; # variable
if ($y <= $x) # test expression
{
$msg = "CIS245!"; # variable
}
print "$msg</body></html>";
X must be the correct drive name
39
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",
"<!Doctype html>",
"<html><body>",
"<h1>Hello, World!</h1>",
"</body></html>";
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 "<!Doctype html>";
print "<html><body>";
sub Hello
{
print "Hello, World!";
}
Hello(); #call the subroutine
print "</body></html>";
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
Types and
Variables
Perl has three built-in data types: scalars, arrays, and hashes. A scalar is either a single string
or a number in most of the cases. Yet, it can also be a reference to something. A sting literal is
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
character: 2, 3, and 9. “45.5” does not mean a value of forty-five and a half. It is a combination
40
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 null character 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 newline.
#!"X:\xampp\perl\bin\perl.exe"
print length(""), "\n<br>";
print length(" "), "\n<br>";
print length(''), "\n<br>";
print length(' '), "\n<br>";
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 <br> HTML tag.
#!"X:\xampp\perl\bin\perl.exe"
print "Content-Type: text/html\n\n";
41
print "<!Doctype html>";
print "<html><body>";
print 627, "\n<br>";
print 345.29, "\n<br>";
print .23E-10, "\n<br>";
print 0xff, "\n<br>";
print 0377, "\n<br>";
print 0b011011, "\n<br>";
print "</body></html>";
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
$age
$firstName
$Student_ID
$bloodType
double x
float age
string firstName
string Student_ID
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 "<!Doctype html>";
42
print "<html><body>";
$x = 3.12;
$age = 41;
$firstName = "Jennifer";
$Student_ID = "D004821256";
$bloodType = 'A';
$score = "";
print "</body></html>";
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 "<!Doctype html>";
print "<html><body>";
$x = 3.12;
$age = 41;
$firstName = "Jennifer";
$Student_ID = "D004821256";
$bloodType = 'A';
$score = "";
print $x, "\n<br>";
print $age, "\n<br>";
print $firstName, "\n<br>";
print $Student_ID, "\n<br>";
print $bloodType, "\n<br>";
print "</body></html>";
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 "<!Doctype html>";
print "<html><body>";
$animal = "camel";
$answer = 42;
$weight = 183.57;
print "There are $answer $animal!\n<br>The square of $weight is
", $weight * $weight, "!";
print "</body></html>";
43
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 "<!Doctype html>";
print "<html><body>";
($a, $b) = (2, 4);
print $a, "\n<br>";
print $b, "\n<br>";
($x, $y, $z) = (5, 7, 9);
print $x, "\n<br>";
print $y, "\n<br>";
print $z, "\n<br>";
print "</body></html>";
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 .
44
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 "<!Doctype html>";
print "<html><body>";
use constant
{
SEC => 0,
MIN => 0,
HOUR => 0,
MDAY => 1,
MON => 0,
YEAR => 2025,
};
print "2025 New Year Day<br>";
print MDAY, "/", (MON+1), "/", YEAR, " ", HOUR, ":", MIN, ":",
SEC;
print "</body></html>";
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");
45
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 "<!Doctype html>";
print "<html><body>";
@x = (25, 30, 40, 45);
@major = ("CIS", "MIS", "IST");
print $x[2], "\n<br>";
print $major[0];
print "</body></html>";
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 "<!Doctype html>";
print "<html><body>";
%state = ("CA", "California", "WA", "Washington", "PA",
"Pennsylvania");
46
print $state{PA}, "\n<br>";
print "</body></html>";
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 "<!Doctype html>";
print "<html><body>";
print "File name: ". __FILE__ . "\n<br>";
print "Line Number: " . __LINE__ ."\n<br>";
print "Package: " . __PACKAGE__ ."\n<br>";
print "</body></html>";
The variable $ENV is a special associative array within Perl that holds the contents of your
shell environment variables. The syntax is:
$ENV{'variableName'}
Perl supports the following environment variables through CGI.
Environment Variable Description
GATEWAY_INTERFACE The revision of the Common Gateway Interface that the server
uses.
SERVER_NAME The server's hostname or IP address.
SERVER_SOFTWARE The name and version of the server software that is answering
the client request.
SERVER_PROTOCOL The name and revision of the information protocol the request
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.
PATH_TRANSLATED The translated version of the path given by the variable
PATH_INFO.
SCRIPT_NAME The virtual path (e.g., /cgi-bin/program.pl) of the script being
executed.
47
DOCUMENT_ROOT The directory from which Web documents are served.
QUERY_STRING The query information passed to the program. It is appended to
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.
REMOTE_IDENT
The user making the request. This variable will only be set if
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".
CONTENT_LENGTH The length of the data (in bytes or the number of characters)
passed to the CGI program through standard input.
HTTP_FROM The email address of the user making the request. Most
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.
HTTP_REFERER The URL of the document that the client points to before
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 "<!Doctype html>";
print "<html><body>";
print "Server Name: ", $ENV{'SERVER_NAME'}, "<br>\n";
print "Running on Port: ", $ENV{'SERVER_PORT'}, "<br>\n";
print "Server Software: ", $ENV{'SERVER_SOFTWARE'}, "<br>\n";
print "Server Protocol: ", $ENV{'SERVER_PROTOCOL'}, "<br>\n";
print "CGI Revision: ", $ENV{'GATEWAY_INTERFACE'}, "<br>\n";
print "</body></html>";
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 "<!Doctype html>";
print "<html><body>";
if (param)
{
$fn = param("fn");
print "Welcome, $fn!";
}
else
48
{
print "<form action='$ENV{SCRIPT_NAME}' method='post'>";
print "Enter your full name: <input type='text' name='fn'>";
print "<input type='submit' value='Go'>";
print "</form>";
}
print "</body></html>";
Perl
Comments
In Perl, the # (pound sign or sharp sign) to indicate the beginning of one-line comments. Any
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 "<!Doctype html>";
print "<html><body>";
print "My name is Nicole Kidman."; # display Nicole Kidman
print "</body></html>";
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 "<!Doctype html>";
print "<html><body>";
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 "</body></html>";
Quotation
Marks May
Matter
When working with strings in Perl, there is a difference between single (‘) and double (“)
quotation marks. If you surround a string with single quote marks, Perl will use the string
directly, without substituting the variable definitions first.
49
#!"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 "<html><body>";
$name1="Jennifer Lopez";
$name2="Lea Thompson";
print "$name1", "<br>";
print '$name2', "<br>";
print "</body></html>";
The output on a browser looks like this:
Jennifer Lopez
$name2
In the Command Prompt, the output looks:
Content-Type: text/html
Jennifer Lopez<br>$name2<br>
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.";
50
## $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
Sequence
Perl supports “escape characters”. Character combinations consisting of a backslash (\),such as
“\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 "<html>\n<head>\n",
"\t<title>Test Page</title>\n</head>\n\n",
"\U<body>\n\n";
print "\U</body></html>";
51
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
<html>
<head>
<title>Test Page</title>
</head>
<BODY>
</BODY></HTML>
You have create several sample Perl scripts with the escape character, “\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 <br> 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<br>Line2";
Many Perl code samples used in later lecture will contain the “\n<br>” combination. The “\n”
part is for Perl interpreter, while “<br>” 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";
52
Making the
script safer
Perl by default is a loosely design langauge. In order to make Perl script more rigid and robust,
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"
print "Content-Type:
text/html\n\n";
print "<!Doctype html>";
print "<html><body>";
$name1="Jennifer Lopez";
$name2="Lea Thompson";
print "$name1", "<br>";
print '$name2', "<br>";
print "</body></html>";
#!"X:\xampp\perl\bin\perl.exe"
use strict;
print "<!Doctype html>";
print "Content-Type:
text/html\n\n";
print "<html><body>";
my $name1="Jennifer Lopez";
my $name2="Lea Thompson";
print "$name1", "<br>";
print '$name2', "<br>";
print "</body></html>";
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;
}
53
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 "<!Doctype html>";
54
print "<html><body>";
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 "</body></html>";
Review
Questions
1. Given the following code segment, which is a small unit of information called a token?
$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 "<html>\n<head>\n</head>\n<body>\n</body>\n<html>";
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
55
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
56
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!
Press any key to continue . . .
Do you want to refresh the XAMPP
installation?
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:
57
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";
print "<!Doctype html>";
print "<html><body>";
print "<h1>This is heading 1.</h1>", # comma
"<h2>This is heading 2.</h2>",
"<h3>This is heading 3.</h3>",
"<h4>This is heading 4.</h4>",
"<h5>This is heading 5.</h5>",
"<h6>This is heading 6.</h6>";
print length(""), "\n<br>";
print length(" "), "\n<br>";
print length(''), "\n<br>";
print length(' '), "\n<br>";
print 627, "\n<br>";
print 345.29, "\n<br>";
print .23E-10, "\n<br>";
print 0xff, "\n<br>";
print 0377, "\n<br>";
print 0b011011, "\n<br>";
$x = 3.12;
$age = 41;
$firstName = "Jennifer";
$Student_ID = "D004821256";
$bloodType = 'A';
$score = "";
print $x, "\n<br>";
print $age, "\n<br>";
print $firstName, "\n<br>";
print $Student_ID, "\n<br>";
print $bloodType, "\n<br>";
print "</body></html>";
2. Use Web browser to visit http://localhost/myperl/lab2_1.pl (where “localhost” is your computer), 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:
\n insert a new line
58
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
<!Doctype html><html><body><h1>This is heading 1.</h1><h2>This is heading
2.</h2><h3>This is heading 3.</h3><h4>This is heading 4.</h4><h5>This is heading
5.</h5><h6>This is heading 6.</h6>0
<br>1
<br>0
<br>1
<br>627
<br>345.29
<br>2.3e-011
<br>255
<br>255
<br>27
<br>3.12
<br>41
<br>Jennifer
<br>D004821256
<br>A
<br></body></html>
Learning Activity #2:
59
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 "<!Doctype html>";
print "<html><body>";
#variables
$animal = "camel";
$answer = 42;
$weight = 183.57;
print "There are $answer $animal.\n<br>The square of $weight is ", $weight *
$weight, ".\n<br>";
#constant
use constant PI => 3.14195;
$r = 15;
print "Circumference is ", 2 * PI * $r, ".\n<br>";
#constants
use constant true => 1;
use constant false => 0;
if (3>5) { print true, "\n<br>"; }
else { print false, "\n<br>"; }
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<br>";
print Plank_constant, "\n<br>";
print Avogadro_constant, "\n<br>";
print Faraday_constant, "\n<br>";
print Coulomb_constant, "\n<br>";
print "</body></html>";
2. Test the program with a web browser. The output is similar to:
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 #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 "<!Doctype html>";
print "<html><body>";
print "File name: ". __FILE__ . "\n<br>";
print "Line Number: " . __LINE__ ."\n<br>";
print "Package: " . __PACKAGE__ ."\n<br>";
#array
@x = (25, 30, 40, 45);
@major = ("CIS", "MIS", "IST");
print $x[2], "\n<br>";
print $major[0], "\n<br>";
#hash
%state = ("CA", "California", "WA", "Washington", "PA", "Pennsylvania");
print $state{PA}, "\n<br>";
=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<br>";
print "$str", "\n<br>";
$name1="Jennifer Lopez";
$name2="Lea Thompson";
print "$name1", "\n<br>";
print '$name2', "\n<br>";
print "\Uthis line must be converted to uppercase.", "\n<br>";
print "\LTHIS LINE MUST BE CONVERTED TO LOWERCASE.", "\n<br>";
print "</body></html>";
2. Test the program with a web browser. The output looks:
61
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 "<!Doctype html>";
print "<html><body>";
my $x = 3.12;
my $age = 41;
my $firstName = "Jennifer";
my $Student_ID = "D004821256";
my $bloodType = 'A';
my $score = "";
print $x, "\n<br>";
print $age, "\n<br>";
print $firstName, "\n<br>";
print $Student_ID, "\n<br>";
print $bloodType, "\n<br>";
my @x = (25, 30, 40, 45);
my @major = ("CIS", "MIS", "IST");
print $x[3], "\n<br>";
print $major[2], "\n<br>";
my %state = ("CA", "California", "WA", "Washington", "PA", "Pennsylvania");
print $state{CA}, "\n<br>";
my $str;
for (my $i=0; $i<=5; $i++)
{
$str .= $i;
}
print $str;
print "</body></html>";
62
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 "<!Doctype html>";
print "<html><body>";
use constant {
SEC => 0,
MIN => 0,
HOUR => 0,
MDAY => 1,
MON => 0,
YEAR => 2025,
};
print "2025 New Year Day<br>";
print MDAY, "/", (MON+1), "/", YEAR, " ", HOUR, ":", MIN, ":", SEC, "\n<br>";
for (1..10)
{
print $_, " ";
}
print "\n<br>";
($a, $b) = (2, 4);
print $a, "\n<br>";
print $b, "\n<br>";
($x, $y, $z) = (5, 7, 9);
print $x, "\n<br>";
print $y, "\n<br>";
print $z, "\n<br>";
print "Server Name: ", $ENV{'SERVER_NAME'}, "<br>\n";
print "Running on Port: ", $ENV{'SERVER_PORT'}, "<br>\n";
print "Server Software: ", $ENV{'SERVER_SOFTWARE'}, "<br>\n";
print "Server Protocol: ", $ENV{'SERVER_PROTOCOL'}, "<br>\n";
print "CGI Revision: ", $ENV{'GATEWAY_INTERFACE'}, "<br>\n";
print "<p>The script name is ", $ENV{SCRIPT_NAME};
63
print "</body></html>";
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.
64
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.