4. Perl
Programming Language Basics
4.1 Introduction
As we mentioned earlier, Perl (Practical Extraction Report
Language) is an interpreted language primarily used as a tool for performing
such functions as manipulate text in files, manipulate files and computer
running processes, extract data from files, automat report writing, perform
networking tasks, generate dynamic HTML pages, process HTML form data through
Perl CGI scripts, and interface to databases.
Perl is a free-form language no declaration needed for
variables. Perl supports three types of variables including scalar, array, and
associative array. All variable names are case sensitive. In this chapter, we
will cover literal constants, variables, escape sequences, Perl expressions and
operators, and control structures. Perl for Windows is available
from www.activestate.com.
Constants
-
Integer constants:
Octal: 0,
1, 2, 3, 4, 5, 6, 7
Decimal:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
hexadecimal:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f or (A, B, C, D, E, F)
-
ASCII character constants:
a, A,
.. z, Z, 0, 1, 2,
9
String
constants:
The Perl
programming Language
W
Floating-point
number constants
123.0 0.0 0.1E-6
Operators
-
Used to combine primitive expressions into complex
expression
-
Arithmetic operators: math computation
-
Logic operations: logic operation and reasoning
-
Relational operator: comparison and reasoning
Variables (Identifiers)
-
A variable is a name which is associated with a value during
the execution of a program
-
A variable starts with one of the special symbols ($, @, %)
can be a sequence of letters, digits, underscores
-
Three types of variables are
-
Scalar variable: $amount
-
Array variable: @pinNoArray
-
Hash array: %countryCode
-
Perl variables are case sensitive (lower and upper -case
letters are treated differently)
-
Perl variables can be defined to have global scope, local
within a block scope through local() function, and strict local block scope
through my() function
Expressions
-
A statement
-
Part of a statement
-
Examples:
Test portion of if statement
$x + $y
$value - $sum /10
Statements
·
Used to describe some program actions, execute for its
effect
·
Types of Statements
-
Declaration statement
-
Expression statement (arithmetic operations, assignment,
function calls)
-
Compound statements (a series of statement to be treated as
a single statement)
-
Selection statement (if, else)
-
Iteration statement (while, do, for)
Subroutine
-
In Perl, subroutine is equivalent to a function or
procedures in other programming languages. A subroutine provides a convenient
way to group some commonly used computation, input and output activities for
modularity and reusability.
Parameters
-
Temporary variables used in the function for holding values
or references passed over from a function or subroutine caller.
Arguments
-
Variables of a function caller for holding temporary values
that are to be passed to a subroutine or function.
4.3 Literal Constants
123
0123
0x43 --
Hexadecimal number
99.56
If there
are two statements in a program:
$currency = 99;
print "Amount: $currency";
It will
access values of variable and display:
Amount: 99
Literal quotes, will not access
values of variable. If there are two statements in a program:
$currency = 99;
print 'Amount: $currency';
It will
access values of variable and display:
Amount: $currency
4.4 Escape Sequences
Escape sequences are control characters that can be used in
Perl statements for character display manipulation. New line characters are
always needed in printing.
\a Bell or a beep
\b Backspace
\e Escape
\f Form feed
\l Change the next character into lower case
\L Change all following characters into
lowercase
\u Change the next character into uppercase
\U Change all following characters into
uppercase
\Q Quote meta-characters as literals
\E Terminate the \L, \Q, or \U sequence
\\ To display a back slash
\n To issue a new line
\r Carriage return
\t Tab
\v Vertical tab
\$ To print a dollar sign
\@ To print an ampersand sign
\0nnn To specify an
octal number in byte
\xnn To specify a hexadecimal number in byte
4.5 Variables
There are three kinds of variables in the Perl:
$address
$first_name
$last_name
@personal_info
Scalar Variables
Two scalar variables begins with a dollar sign $ are
defined:
$currency
= 100;
$country
= "Taiwan";
$Voltage
= 110;
$Current
= 30;
$HorsePower
= 10;
$NumberOfPhase
= 3;
$ControlPanels
= 20;
$ManulTitle = "Data Acquisition Card DT330";
Array variables
An array variable starts with the @ sign. It can hold
several pieces of data of the same type or different type. For a regular array, a pair of parentheses (
) is used to initialized the array and a pair brackets [ ] is used for
indexing.
Examples: Array initialization and manipulation
@numArray = (); # An empty array
@mixedArray =
("Equipment Name", "Cost", 1000.0, 08, 123);
@number1 = (0, 1, 2,
3, 4, 5, 6, 7, 8, 9);
·
Using a range of values: Uses two period (..) to replace a
consecutive series of values
The array @number1 should
hold the same elements as the array @number2:
@number2 = (0 .. 9);
Two character arrays for holding uppercase letter A, B, C,
..Z and lower case letters:
@upchar_array =
(A..Z);
@lowchar_array =
(a..z);
print
"@upchar_array \n"; # print
all char in the array
print "@upchar_array[0]
\n"; # print the first element
print
"@upchar_array[25] \n"; #
print the last element
·
Define and initialized name array for holding eight names
of professors:
@professors =
("Lin", "Emery", "Broberg",
"Leveghetta", "Hack", "Steffen", "Omiston",
"Disher");
The individual element of the array can then be accessed
through the following syntax:
print
"Professor : $professors[0]\n";
print
"Professor : $professors[1]\n";
print
"Professor : $professors[5]\n";
Results
Professor:
Lin
Professor:
Emery
Professor:
Steffen
·
Array Merging
@myarray =
("1", "two",
"three", 4);
#
define an array of that holds data of different types
($first_element,
$second_element, $third_element, $fourth_element) = @myarray;
# assign scalar variables with array's
content
@newarray = (0,
@myarray, 5);
#
now we create a new array with five different elements in
#
it: ("0", "1", "two", "three", 4, 5)
·
Array Element and Size Calculation
$last_index =
$#array;
#
The index of the last element of the array is 3
$array_size =
$last_index +1;
#
The number of element in the array is 4 since array index
#
starts at 1
$last =
@array($#array);
# Assign the last element of the array
into $last variable
Associative array
An associative array is indicated by adding a percent sign,
%, in front of a variable name. A pair of parentheses ( ) is used to
initialized the array and a pair braces { } is used for indexing. The array is
indexed by strings.
Examples:
# Define a database
for saying different HELLO messages
%web_greeting =
(
'com', 'hello', # US Commercial sites
'edu', 'hi', # US educational sites
'mil', 'Sir', # US military sites
'fr',
'Bonjour', # Franch
'mx',
'hola', # Maxico
'tw',
'NeeHou', # Taiwan
'jp',
'KonNiChiWa' #Japan
);
4.6 Perl Expressions and Operators
Perl language defines a set of operators that is richer than
the C programming language. The meaning of operators and examples are listed
below.
Special Symbols
# Starts one line comment
& Added before a name of subroutine when
called
$ Scalar variable
@ Array variable
@_ A system parameter array
" " For quoting a string with variables
' ' For quoting literal string
Binary Arithmetic
Operators
+ Addition operator: $op = $op1 + $op2; #($op holds 30)
- Subtraction operator: $op = $op1 - $op2; #($op holds -10)
* Multiplication: $op = $op1 * $op2;
#($op holds 100)
/ Division: $op = $op1 / $op2; #($op holds 0.5)
% Remainder or modulus: $op = $op1 % $op2; #($op holds 10)
** Exponentiation: $op = $op1 ** 3; #($op hold 1000)
Unary Arithmetic
Operators
+ Positive operand: +10
- Negative operand: -10
++ Increment by 1:
$num = 10;
$op = ++$num; #pre-increment ($op holds 11)
$op = $num++; #post-increment ($op holds 10)
-- Decrement by 1:
$num = 10;
$op = --$num; #pre-increment ($op holds 9)
$op = $num--; #post-increment ($op holds 10)
Relational
Operators
== Equal to
!= Not Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
<=> Greater than (return 1); Equal to (return
0); Less than
(return
-1)
Logical Operators
&& AND operator
|| OR operator
! NOT operator
The Bit-Wise
Operators
~ Bit-wise NOT: $op = ~0x01; #(result 0xFE or 254)
& Bit-wise AND: $op = 0x02 & 0x01; #(result 0x00)
| Bit-wise OR: $op = 0x02 | 0x01; #(result 0x03)
^ Bit-wise EXOR: $op = 0x0F ^ 0xF0; #(result 0xFF or 255)
>> Shift Right: Shift
right one bit is the same as div by 2
$num
= 8; $op = $num >> 2; #($op holds 2)
<< Shift Left: Shift left one bit is the same as times 2
$num
= 8; $op = $num << 2; #($op holds 32)
Assignment
Operators
= Assignment
+= Add and assign
-= Sub and assign
*= Multiply and assign
/= Divide and assign
%= Remainder and assign
**= Exponentiation and assign
<<= Shift left and assign
>>= Shift right and assign
&= Bit-wise AND and assign
|= Bit-wise OR and assign
^= Bit-wise XOR and assign
Relational
Operators for String Comparisons
eq Equal to: if($op1 eq $op2)
ne Not Equal to: if($op1 ne $op2)
lt Less than: if("c"
lt "b")
le Less than or equal to: if("b" le "c"
gt Greater than: if("c"
gt "b")
ge Greater than or equal to: if("b"
ge "c")
cmp Greater than (return 1); Equal to (return
0); Less than
(return
-1): if($op1
cmp $op2)
The Ternary
Operator
The conditional
statement: if -- else in Perl such as
if(Expession)
Exp1;
else
Exp2;
Can be written with
the ternary operator:
(Expession?)
Exp1: Exp2;
The Range
operator
.. For defining a range of numbers in the array
@array = (0 .. 9); # 0, 1, 2, .., 9
@letters = ("aa" ..
"ae"); # aa, ab, ac, ad, ae
The String
Operators
. Concatenation of strings
Example:
$newstring
= "Amount due " . "=". 30 . "dollars" ;
x Repetition
Example:
$asciinum = "2";
$numstr = $asciinum x 4; # $numstr holds "2222"
Matching Operator
=~ For testing a string or pattern within a
single string of words
4.7 Control Structures
To enforce the order of computation, Perl supports a rich
set of control structures as described below.
Decision making (if, else, elseif)
if(statement) # Test the true-false condition of the
statement
elseif(statement) # Placed after the if(statement) to test another
#
condition
else(statement) # Used at the end of if block
Loop Iteration Control
·
For Loop Example:
for($count = 0;
$count < 10; $count++)
{
$count++;
print "Count = $count";
}
·
while Loop Example:
$count = 0;
while($count <
10)
{
$count++;
print "Count = $count";
}
·
do/while Loop Example:
$count = 0;
do
{
$count++;
print "Count = $count";
} while($count < 10);
·
do/until Loop Example:
$count = 0;
do
{
$count++;
print "Count = $count";
} until($count > 10);
·
foreach Loop Example
foreach control takes a list of values and assign them on at
a time to a scalar variable.
Example:
#rev_foreach.pl
@numArray = (0, 1, 2, 3, 4);
@revArray = ();
print "Numarray before reversing: ";
print "@numArray\n\n";
$i = 0;
foreach $nowNum (reverse @numArray)
{
print
"$nowNum\n";
@revArray[$i] =
$nowNum;
$i = $i + 1;
}
print "Numarray after reversing: @numArray\n\n";
print "New array: @revArray\n\n";
OUTPUT
E:\Perl\Exs>perl rev_foreach.pl
Numarray before reversing: 0 1 2 3 4
4
3
2
1
0
Numarray after reversing: 0 1 2 3 4
New array: 4 3 2 1 0
until(condition_false) # if true don't execute the statement block
{
statement1;
statement2;
}
·
The last Statement
for breaking out the innermost loop block
Example:
$count = 0;
$stop = 100;
while($count <
10)
{
$count++;
print "Count = $count";
if($stop == 0)
{
print "Will be stopped\n";
last;
}
$stop--;
}
print "All
done\n"; # last will come here
·
The next Statement
The next causes execution to skip past the rest of the
innermost enclosing block without terminating the block.
$count = 0;
$stop = 100;
while($count <
10)
{
$count++;
print "Count = $count";
if($stop == 0)
{
print "Will be stopped\n";
next;
}
$stop--;
# next will come here
}
print "All
done\n"; # last will come here
·
The redo Statement
The redo statement allow program to go back in the loop.
$count = 0;
$stop = 100;
while($count <
10)
{
# redo will come here
$count++;
print "Count = $count";
if($stop == 0)
{
print "Will be stopped\n";
redo;
}
$stop--;
}
print "All
done\n"; # last will come here