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
27
Embed
Lecture #2 Perl Syntaxes declaration statements …students.cypresscollege.edu/cis245/lc02.pdfor a reference. A Perl variable names begin with a dollar sign ($). They can be any combination
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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.
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