welcome to perl programming by paul chin jonathan ong inti industrial training centre

127
Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Post on 19-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Welcome to Perl Programming

by Paul Chin

Jonathan Ong

INTI Industrial Training Centre

Page 2: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 1, Lesson 01 (D1L01)

Introduction to Perl What is Perl? What do I need to get started? Where can I get Perl?

Page 3: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L01: What is Perl?

A scripting language for easily manipulating text, files, and processes.

Perl is mostly used on Unix systems However, a Windows version of Perl is also available but it is

less powerful than its Unix counterpart and rarely used Perl is short for "Practical Extraction and Report Language," Perl is interpreted (no compilation necessary) Combines many features found in shell scripts and C. Has all the functionality of sed and awk. Very popular with Unix systems programmers and web

designers

Page 4: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L01: Why should I learn Perl?

Similar syntax to C- looks familiar to most programmers Extremely expressive- a few lines of code will do a lot Very suitable for creating small utility programs - which

otherwise takes to much hassle to code in C Works very well together with the UNIX operating system-

such as Solaris, Linux, etc. Great for creating one-time or “throw-away“ programs- little

programs that you need to use only once or twice You need it to be a UNIX guru- any self respecting UNIX pro

need to know Perl well Because Perl fetches good prices on the jewelry market-

just kidding!

Page 5: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L01: What do I need to get started?

You need basic knowledge of Unix commands You need a working copy of Perl installed on your

system.– Type perl -v to check whether Perl is installed.– Perl is usually already installed on most Unix systems

(including Linux)

You need a Text Editor (such as vi, kwrite)– Make sure your file is executable (chmod ugo+x

<filename>)– Add the following line to the beginning of your file:

#!/usr/bin/perl

Page 6: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L01: Where can I get Perl?

New versions of Perl are released on the Internet and distributed to Web sites and ftp archives across the world.

As with most Unix software, Perl is usually distributed as source code; you have to compile it before you can use it.

However, “packaged “ versions of Perl are available on systems such as RedHat Linux which greatly simplifies installation.

A free Windows version of Perl is available at: http://www.activestate.com

Refer to textbook for more details on this topic.

Page 7: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 1, Lesson 02 (D1L02)

Your first Perl program Hello, world! The print command Perl statements Using perl interpreter

Page 8: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L02: Hello, world!

Create a new file with your text editor, eg, kwrite. Name the file hello.pl. This is how to write your very first little Perl program:

#!/usr/bin/perl -w

print ("Hello, world!\n");

Now save the file. Open an xterm. You will see a shell prompt: $ Type perl hello.pl or ./hello.pl

You should see the following on your console:

Hello, world!

Page 9: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L02: The “print”command

Prints a string or a list of strings Similar to C’s printf. One of the most commonly used command

print("hello world\n"); # say hello world, followed by newline

print "hello world\n"; # same thing NOTE: The second example shows the form of print without

parentheses. Whether or not to use the parentheses is mostly a matter of style and typing agility, although there are a few cases where you'll need the parentheses to remove ambiguity.

On Unix/Linux, you could also run perl commands from the shell: perl <enter> print “Hello world\n”; <enter> ^d ^d (ctrl d) is the EOF character.

Page 10: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L02: Perl statements

As in C, all simple statements in Perl are terminated by a semicolon.

The semicolon can be omitted when the statement is the last statement of a block or file

Perl comments begin with the pound sign #.

The first line of a Perl program is a special comment; unlike other comments Perl actually looks at that line for any optional arguments. (see above)

The first line also indicates that this is a Perl program. To find out where the perl interpreter is located, type: whereis perl

at the command line shell prompt.

TIP: The –w option instructs Perl to produce extra warning messages. You should always develop your programs under -w.

#!/usr/bin/perl -w

Page 11: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L02: The Perl interpreter

Perl interpreter completely parses (reads) and compiles the source code of your program into an internal format before executing any of it.

You call the Perl interpreter through the first line of the perl script, ie, #!/usr/bin/perl

TIP: perl is case-sensitive. Also, the location of the interpreter differs from one system to another. Be sure to locate it using the command

whereis. Also set the file to executable by using chmod.

The example runs the hello.pl program as follows:

perl hello.pl ./hello.pl

The ./ that precedes the script name is to tell the OS to look within the present directory, ie the directory that hello.pl resides

Page 12: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 1, Lesson 03 (D1L03)

Operators

Scalar Operator– Arithmetic operators: +, -, *, /, %, ** (exp), ++, --– Assignment Operators: = ,+=, -=, .=

– String Operations: . , substr()– Logical operators: &&, ||, !

Page 13: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L03: Scalar Operators

An operator produces a new value (the result) from one or more other values (the operands). For example, + is an operator because it takes two numbers (the operands, like 5 and 6), and produces a new value (11, the result).

$x=5;

$y=6;

$z=$x+$y;

print $z;

NOTE: A scalar is the simplest kind of data that Perl manipulates. A scalar is either a number (like 5) or a string of characters (like “hello” or “Intel”).

Page 14: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L03: More on scalars

Holds a single value (either a string or a number) Perl will treat it as a string or number depending on

the context. References to scalar variables always begin with a $

even if they are part of an array. No declaration necessary

$NUMBER = 42;$NAME = ’jon’;$MESSAGE = “Intel Corporation”;

Page 15: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L03: Arithmetic Operators

Perl provides the typical ordinary addition, subtraction, multiplication, and division operators and so on.

For example:2 + 3 # 2 plus 3, or 5

5.1 - 2.4 # 5.1 minus 2.4, or approximately 2.7

3 * 12 # 3 times 12 = 36

14 / 2 # 14 divided by 2, or 7

10 / 3 # always floating point divide, so approximately 3.3333333...

10 % 3 # the remainder when 10 is divided by 3, which is 1

2**3 # 2 to the power of 3, which is 8

Exercise:Write a program to evaluate this expression: (7+5)/6

Page 16: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L03: Assignment Operators

The Perl assignment operator is the equal sign (much like C or FORTRAN), which takes a variable name on the left side and gives it the value of the expression on the right, like so:

Scalar variables are always specified with the leading $. Just like C, Perl allows you to use binary assignment operators to save on key strokes:

$a = 17; # give $a the value of 17

$b = $a + 3; # give $b the current value of $a plus 3 (20)

$b = $b * 2; # give $b the value of $b multiplied by 2 (40)

$a = $a + 5; # without the binary assignment operator$a += 5; # with the binary assignment operator

$b = $b * 3;$b *= 3;

Page 17: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L03: Other Binary Operators

The ++ operator (called the autoincrement operator) adds one to its operand, and returns the incremented value, like so:

The autodecrement operator (--) is similar to the autoincrement operator, but subtracts one rather than adding one.

$a += 1; # with assignment operator++$a; # with prefix autoincrement$a++; # another syntax for autoincrement$d = 17;$e = ++$d; # $e and $d are both 18 now

Page 18: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L03: String Operators

String values can be concatenated with the "." operator. (Yes, that's a single full-stop.)

This does not alter either string, any more than 2+3 alters either 2 or 3. The resulting (longer) string is then available for further computation or to be stored into a variable.

Another string operator is the string repetition operator, consisting of the single lowercase letter x:

"hello" . "world" # same as "helloworld"'hello world' . "\n" # same as "hello world\n""fred" . " " . "barney" # same as "fred barney"

"fred" x 3 # is "fredfredfred"

Exercise: Write a program to input your name and print: “Good morning <yourname>”

Page 19: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L03: Comparison Operators

The comparison operators for numbers are < <= == >= > !=, these compare two values numerically, returning a true or false value.

Another set of operators for strings are the string comparison operators. The operators compare the ASCII values of the characters of the strings.

ge>=Greater than or equal to

le<=Less than or equal to

gt>Greater than

lt<Less than

ne!=Not equal

eq==Equal

String

Numeric

Comparison

NOTE: If you come from a UNIX shell programming background, the numeric and string comparisons are roughly opposite of what they are for the UNIX which uses -eq for numeric comparison and = for string comparison.

Page 20: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 1, Lesson 04 (D1L04)

Flow Control Statement blocks if-else and elsif statements while and until statements for and foreach statements

Note: elsif is correct, elseif is wrong!

Page 21: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: Statement blocks

A statement block is a sequence of statements, enclosed in matching curly braces. It looks like this:

{first_statement;second_statement;third_statement;...last_statement;

}

TIP: The final semicolon on the last statement is optional. Thus, you can speak Perl with a C-accent (semicolon present) or Pascal-accent (semicolon absent).

Page 22: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: “if-else” statements

An “if” statement takes a control expression (evaluated for its truth) and a block.

It may optionally have an else followed by a block as well.

For example:

if (some_expression) {true_statement_1;true_statement_2;true_statement_3;

} else {false_statement_1;false_statement_2;false_statement_3;

}

Page 23: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: More on “if-else” statements

During execution, Perl evaluates the control expression. If the expression is true, the first block (the true_statement statements above) is executed. If the expression is false, the second block (the false_statement statements above) is executed instead. (refer to previous slide)

But what constitutes true and false? Here are some examples of true and false interpretations:

0 # converts to "0", so false

1-1 # computes to 0, then converts to "0", so false

1 # converts to "1", so true

"" # empty string, so false

"1" # not "" or "0", so true

"00" # not "" or "0", so true (this is weird, watch out)

"0.000" # also true for the same reason and warning

undef # evaluates to "", so false

Page 24: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: More on “if-else” statements

print “How old are you? ";

$a = <STDIN>;

chomp($a);

if ($a < 21) {

print "So, you're not old enough to vote, eh?\n";

} else {

print "Old enough! Cool! So go vote!\n";

}

Here's an example of a complete “if” statement:

NOTE: The chomp function takes a scalar variable as its sole argument and removes the trailing newline (record separator). More on chomp later.

NOTE: <STDIN> gets input from the standard input (stdin) right until the first newline (\n) character. It is similar to C's fgets() function.

Page 25: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: More on “if-else” statements

print "how old are you? ";

$a = <STDIN>;

chomp($a);

unless ($a < 21) {

print "Old enough! Cool! So go vote!\n";

}

Sometimes, you want to leave off the "then" part and have just an else part, because it is more natural to say "do that if this is false," rather than "do that if not this is true." Perl handles this with the unless variation:

TIP: An unless can also have an else, just like an if.

Page 26: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: More on “if-else” statements

if (some_expression_one) {

one_true_statement_1;

one_true_statement_2;

} elsif (some_expression_two) {

two_true_statement_1;

two_true_statement_2;

} elsif (some_expression_three) {

three_true_statement_1;

three_true_statement_2;

} else {

all_false_statement_1;

all_false_statement_2;

}

Note: elsif

not elseif

If you have more than two possible choices, add an “elsif” branch to the if statement, like so:

Page 27: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: “while” statements

No programming language would be complete without some form of iteration (repeated execution of a block of statements). Perl can iterate (loop) using the while statement:

while (some_expression) {

statement_1;

statement_2;

statement_3;

}

Page 28: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: More on “while” statements

To execute this while statement, Perl evaluates the control expression (some_expression in the example). If its value is true the body of the while statement is evaluated once. This is repeated until the control expression becomes false, at which point Perl goes on to the next statement after the while loop. For example:

print "how old are you? ";

$a = <STDIN>;

chomp($a);

while ($a > 0) {

print "At one time, you were $a years old.\n";

$a--;

}

Page 29: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: “until” statements

Sometimes it is easier to say "until something is true" rather than "while not this is true." Once again, Perl has the answer. Replacing the while with until yields the desired effect:

until (some_expression) {

statement_1;

statement_2;

statement_3;

}

Page 30: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: “for” loops

Like in C, a for loop has an initialization statement, a test condition, and an increment statement.

A foreach loop will iterate through each of the elements of a normal array.

for ($i=1; $i<10; $i++) {...

}

foreach $e (@elements) {...

}

Page 31: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L04: Exercises

1. Write a program that computes the circumference of a circle with a radius of 12.5. The circumference is 2 [pi] times the radius, or about 2 times 3.141592654 times the radius. Modify the program from the previous exercise to prompt for and accept a radius from the person running the program.

1. Write a program that prompts for and reads two numbers, and prints out the result of the two numbers multiplied together.

1. Write a program that reads a string and a number, and prints the string the number of times indicated by the number on separate lines. (Hint: use the "x" operator.)

Page 32: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 1, Lesson 05 (D1L05)

Working with Scalars Strings and Escape Sequences Conversion Between Numbers and Strings chop() and chomp()

Page 33: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L05: Strings and Escape Sequences

A single-quoted string is a sequence of characters enclosed in single quotes.

Any character between the quote marks (including newline characters, if the string continues onto successive lines) is legal inside a string.

Two exceptions: to get a single quote into a single-quoted string, precede it by a backslash. And to get a backslash into a double-quoted

string, precede the backslash by a backslash. Examples:

'hello' # five characters: h, e, l, l, o'don\'t' # five characters: d, o, n, single-quote, t'' # the null string (no characters)'silly\\me' # silly, followed by backslash, followed by me'hello\n' # hello followed by backslash followed by n'hellothere' # hello, newline, there (11 characters total)

Single-Quoted Strings

Page 34: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L05: Strings and Escape Sequences

A double-quoted string acts a lot like a C string. Once again, it's a sequence of characters, although this time enclosed

in double quotes. But now the backslash takes on its full power to specify certain control

characters, or even any character at all through octal and hex representations.

'hello' # five characters: h, e, l, l, o"hello world\n" # hello world, and a newline"new \177" # new, space, and the delete character (octal 177)"coke\tsprite" # a coke, a tab, and a sprite

Double-Quoted Strings

Page 35: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L05: Strings and Escape Sequences

If a string value is used as an operand for a numeric operator (say, +), Perl automatically converts the string to its equivalent numeric value, as if it had been entered as a decimal floating-point value.

eg, print “2” + 3; #gives 5

"X" . (4 * 5) # same as "X" . 20, or "X20"

Conversion Between Numbers and Strings

In other words, you don't have to worry about whether you have a number or a string (most of the time). Perl performs all the conversions for you.

Page 36: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L05: Strings and Escape Sequences

Escape Sequences

Terminate \L , \U, or \Q\E

Backslash-quote all nonalphanumerics until \E\Q

Uppercase all following letters until \E\U

Uppercase next letter\u

Lowercase all following letters until \E\L

Lowercase next letter\l

Double quote\"

Backslash\\

Any "control" character (here, CTRL-C)\cC

Any hex ASCII value (here, 7f = delete)\x7f

Any octal ASCII value (here, 007 = bell)\007

Escape\e

Bell\a

Backspace\b

Formfeed\f

Tab\t

Return\r

Newline\n

MeaningConstruct

Page 37: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L05: Strings and Escape Sequences

A very simple but useful function. This function takes a single argument within its parentheses – the name

of a scalar variable - and removes the last character from the string value of that variable.

$x = "hello world";chop($x); # $x is now "hello worl"

chop()

NOTE: If chop is given an empty string, it does nothing, and returns nothing, and doesn't raise an error or even whimper a bit unless you are using the -w switch.

Page 38: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L05: Strings and Escape Sequences

When you chop a string that has already been chopped, another character disappears off into "bit heaven.“ For example:

$a = "hello world\n";chop $a; # $a is now "hello world"chop $a; # oops! $a is now "hello worl“chop $a; # $a is now "hello wor“chop $a; # $a is now "hello wo“chop $a; # $a is now "hello w“

More chop()-ing

In other words, a string get shorter every time you chop off its last character.

Page 39: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L05: Strings and Escape Sequences

If you're not sure whether the variable has a newline on the end, you can use the slightly safer chomp function, which removes only a newline character, like so:

$a = "hello world\n";chomp ($a); # $a is now "hello world"chomp ($a); # aha! no change in $a

chomp

Page 40: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 1, Lesson 06 (D1L06)

Working with lists What Is a List or Array? Array Assignment and Element Access Sorting Using chomp() and chop() Using foreach

Page 41: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: What is a List or Array

A list is ordered scalar data. An array is a variable that holds a list. Each element of the array is a separate scalar variable with an independent scalar value.

These values are ordered; that is, they have a particular sequence from the lowest to the highest element.

Arrays can have any number of elements. The smallest array has no elements, while the largest

array can fill all of available memory. Once again, this is in keeping with Perl's philosophy

of "no necessary limits."

Page 42: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: Array variable

An array variable holds a single list value (zero or more scalar values).

Array variable names are similar to scalar variable names, differing only in the initial character, which is an at sign (@) rather than a dollar sign ($). For example:

@fred # the array variable @fred@A_Very_Long_Array_Variable_Name@A_Very_Long_Array_Variable_Name_that_is_different

Page 43: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: Creating Lists

A list literal (the way you represent the value of a list within your program) consists of comma-separated values enclosed in parentheses. These values form the elements of the list. For example:

(1,2,3) # array of three values 1, 2, and 3("fred",4.5) # two values, "fred" and 4.5

The elements of a list are not necessarily constants; they can be expressions that will be reevaluated each time the literal is used. For example:

($a,17); # two values: the current value of $a, and 17($b+$c,$d+$e) # two values

Page 44: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: List Constructors

An item of the list literal can include the list constructor operator, indicated by two scalar values separated by two consecutive periods.

This operator creates a list of values starting at the left scalar value up through the right scalar value, incrementing by one each time. For example:

(1 .. 5) # same as (1, 2, 3, 4, 5)(1.2 .. 5.2) # same as (1.2, 2.2, 3.2, 4.2, 5.2)(2 .. 6,10,12) # same as (2,3,4,5,6,10,12)($a .. $b) # range determined by current values of $a and $b

Page 45: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: String Lists

List literals with lots of short text strings start to look pretty noisy with all the quotes and commas:

@a = ("fred","barney","betty","wilma"); # ugh!

So there's a shortcut: the "quote word" function:

@a = qw(fred barney betty wilma); # better!@a = qw(

fredbarneybettywilma

); # same thing

Page 46: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: Array Assignment and Element Access

Probably the most important array operator is the array assignment operator, which gives an array variable a value. For example:

@fred = (1,2,3); # The fred array gets a three-element literal@barney = @fred; # now that is copied to @barney

Array variable names may appear in a list literal list. When the value of the list is computed, Perl replaces the names with the current values of the array, like so:

@fred = qw(one two);@barney = (4,5,@fred,6,7); # @barney becomes# (4,5,"one","two",6,7)@barney = (8,@barney); # puts 8 in front of @barney@barney = (@barney,"last");# and a "last" at the end# @barney is now (8,4,5,"one","two",6,7,"last")

Page 47: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: More Array Assignment and Element Access

Perl provides a traditional subscripting function to access an array element by numeric index.

@fred = (7,8,9);$b = $fred[0]; # give 7 to $b (first element of @fred)$fred[0] = 5; # now @fred = (5,8,9)

Perl provides a traditional subscripting function to access an array element by numeric index.

$c = $fred[1]; # give 8 to $c$fred[2]++; # increment the third element of @fred$fred[1] += 4; # add 4 to the second element($fred[0],$fred[1]) = ($fred[1],$fred[0]); # swap the first two

Page 48: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: Slicing and Extending Arrays

Accessing a list of elements from the same array (as in that last example) is called a slice, and occurs often enough that there is a special representation for it:

@fred[0,1]; # same as ($fred[0],$fred[1])@fred[0,1] = @fred[1,0]; # swap the first two elements@fred[0,1,2] = @fred[1,1,1]; # make all 3 elements like the 2nd@fred[1,2] = (9,10); # change the last two values to 9 and 10

Slices also work on literal lists, or any function that returns a list value:

@who = (qw(fred barney betty wilma))[2,3];# like @x = qw(fred barney betty wilma); @who = @x[2,3];

Assigning a value beyond the end of the current array automatically extends the array (giving a value of undef to all intermediate values, if any). For example:

@fred = (1,2,3);$fred[3] = "hi"; # @fred is now (1,2,3,"hi")$fred[6] = "ho"; # @fred is now (1,2,3,"hi",undef,undef,"ho")

Page 49: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: Sorting

The sort function takes its arguments, and sorts them as if they were single strings in ascending ASCII order. It returns the sorted list without altering the original list. For example:

@x = sort("small","medium","large");# @x gets "large","medium","small"@y = (1,2,4,8,16,32,64);@y = sort(@y); # @y gets 1,16,2,32,4,64,8

Exercise:Write a program to reverse sort this list:@a = (“ball”,”apple”,”cat”);

Page 50: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: Using chomp() and chop()

The chomp and chop function works on an array variable as well as a scalar variable. chomp can be handy when you've read a list of lines as separate array elements, and you want to remove the newline from each of the lines at once.

@stuff = ("hello\n","world\n","happy days");chomp(@stuff); # @stuff is now ("hello","world","happy days")

@fruits = (“apples",“oranges",“grapes");chop(@fruit); # @fruits is now (“apple",“orange",“grape")

Page 51: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: Using foreach

@names = (’ted’, ’fred’, ’zed’);

foreach $i (0 .. $#names) {print “$names[$i]\n”;

}

The foreach statement takes a list of values and assigns them one at a time to a scalar variable, executing a block of code with each successive assignment.

foreach is very useful for walking through each element of an array:

Page 52: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D1L06: Exercises

1. Write a program that reads a list of strings on separate lines and prints out the list in reverse order. If you're reading the list from the terminal, you'll probably need to delimit the end of the list by pressing your end-of-file character, probably CTRL-D under UNIX or Plan 9; often CTRL-Z elsewhere.

1. Write a program that reads a number and then a list of strings (all on separate lines), and then prints one of the lines from the list as selected by the number.

1. Write a program that reads a list of strings and then selects and prints a random string from the list. To select a random element of @somearray, put

srand;at the beginning of your program (this initializes the random-number generator), and then use

rand(@somearray)where you need a random value between zero and one less than the length of @somearray.

Page 53: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 2, Lesson 01 (D2L01)

Working with hashes What is a hash? Creating hashes Deleting hash elements Getting hash values and hash keys, looping

Page 54: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L01: What is a hash?

A hash is like the array that we discussed earlier, in that it is a collection of scalar data, with individual elements selected by some index value. Unlike a list array, the index values of a hash are not small nonnegative integers, but instead are arbitrary scalars.

The elements of a hash have no particular order. Consider them instead like a deck of filing cards.

The top half of each card is the key, and the bottom half is the value.

Each time you put a value into the hash, a new card is created. Later, when you want to modify the value, you give the key, and

Perl finds the right card. So, really, the order of the cards is immaterial.

Page 55: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L01: What is an associative array then?

In older documentation, hashes were called "associative arrays," but we got tired of a seven-syllable word for such a common item, so we replaced it with a much nicer one-syllable word.

Page 56: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L01: Creating hashes

A hash variable name is a percent sign (%) followed by a letter, followed by zero or more letters, digits, and underscores.

Each element of the hash is a separate scalar variable, accessed by a string index, called the key.

As with arrays, you create new elements merely by assigning to a hash element:$fred{"aaa"} = "bbb"; # creates key "aaa", value "bbb"$fred{234.5} = 456.7; # creates key "234.5", value 456.7

-- OR --

%fred=(“aaa”,”bbb”,234.5,456.7);

These two statements create two elements in the hash. Subsequent accesses to the same element (using the same key) return the previously stored value:

print $fred{"aaa"}; # prints "bbb"$fred{234.5} += 3; # makes it 459.7

Page 57: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L01: Hash slices

Like an array variable (or list literal), a hash can be sliced to access a collection of elements instead of just one element at a time. For example, consider the bowling scores set individually:

@score{"fred","barney","dino"} = (205,195,30);

-- OR --

%score(“fred”,205,”barney”,195,”dino”,30);

$score{"fred"} = 205;$score{"barney"} = 195;$score{"dino"} = 30;

This seems rather redundant, and in fact can be shortened to:

($score{"fred"},$score{"barney"},$score{"dino"}) = (205,195,30);

But even these seems redundant. Let's use a hash slice:

Page 58: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L01: Deleting hash elements

Perl provides the delete function to remove hash elements. The operand of delete is a hash reference, just as if you were

merely looking at a particular value. Perl removes the key-value pair from the hash. For example:

%fred = ("aaa","bbb",234.5,34.56); # give %fred two elementsdelete $fred{"aaa"};# %fred is now just one key-value pair

Page 59: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L01: Getting hash value and keys

The keys(%hashname) function yields a list of all the current keys in the hash %hashname. In other words, it's like the odd-numbered (first, third, fifth, and so on) elements of the list returned by unwinding %hashname in an array context, and in fact, returns them in that order. If there are no elements to the hash, then keys returns an empty list.

For example, using the hash from the previous examples:

$fred{"aaa"} = "bbb";$fred{234.5} = 456.7;@list = keys(%fred); # @list gets ("aaa",234.5) or(234.5,"aaa")

The values(%hashname) function returns a list of all the current values of the %hashname, in the same order as the keys returned by the keys(%hashname) function. As always, the parentheses are optional. For example:

%lastname = (); # force %lastname empty$lastname{"fred"} = "flintstone";$lastname{"barney"} = "rubble";@lastnames = values(%lastname); # grab the values

Page 60: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L01: Looping

The function “each” extracts each key-value pair:

@hash{“one”,”two”,”three”}=(1,2,3);

while (($key,$value) = each(%hash)) {print "$key->$value\n";

}

Page 61: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 2, Lesson 02 (D2L02)

Working with files What Is a Filehandle? Opening and Closing a Filehandle Reading Lines from a File Writing to a File The –x File Test

Page 62: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L02: What is a file handle?

A filehandle in a Perl program is the name for an I/O connection between your Perl process and the outside world.

We've already seen and used filehandles implicitly: STDIN is a filehandle, naming the connection between the Perl process and the UNIX standard input.

Perl provides three filehandles, STDIN, STDOUT, and STDERR, which are automatically open to files or devices established by the program's parent process (probably the shell).

You use the open function to open additional filehandles.

Page 63: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L02:Opening and Closing a Filehandle

You use the open function to open additional filehandles. The syntax for opening a file for reading looks like this:

open(FILEHANDLE,"somename");

To open a file for writing, use the same open function, but prefix the filename with a greater-than sign (as in the shell):

open(OUT, ">outfile");

Also, as in the shell, you can open a file for appending by using two greater-than signs for a prefix, as in:

open(LOGFILE, ">>mylogFile");

When you are finished with a filehandle, you may close it with the close operator, like so:

close(LOGFILE);

Page 64: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L02: Reading Lines from a File

You use the open function to open additional filehandles. The syntax for opening a file for reading looks like this:

open(IN,$a) || die "cannot open $a for reading: $!";while (<IN>) { # read a line from file $a into $_

print $_; # print that line to file $b}close(IN) || die "can't close $a: $!";

die:

1. Typically you'll want to check the result of the open and report an error if the result is not what you expect. (such as a missing file)

2. The die function takes a list within optional parentheses, spits out that list on the standard error output, and then ends the Perl process with a nonzero exit status.

3. Another handy thing inside die strings is the $! variable, which contains the error string describing the most recent operating system error.

Page 65: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L02: More On Reading from Files

Another example. <filehandle> yields the next line from the file, and false if EOF; by default, stores in $_

open(FILE, “filename”) ||die “Couldn’t open file\n”;

$count = 0;while ($line = <FILE>) { ++$count; print “line $count = $line\n”;} --- OR ---while (<FILE>) { ++$count ; print “line $count = $_\n” ;}close(FILE);

Page 66: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L02: Writing to a File

In Perl, writing data to a file is extremely easy:

open(OUT, ">test.txt");

print OUT “This is some test data.\n";

close(OUT);

You simply print (write) the data to the filehandle. That’s it.

Always remember to close the filehandle after using it.

Page 67: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L02: More On Writing to Files

print has an optional filehandle argument

open(OUT, “>output”) ||die “Couldn’t open file\n”;

for ($i=0; $i<10; $i++) {print OUT “line $i\n”;

}

close(OUT);

Page 68: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L02: The –e File Tests

Now you know how to open a filehandle for output, overwriting any existing file with the same name.

Suppose you wanted to make sure that there wasn't a file by that name (to keep you from accidentally blowing away your spreadsheet data or that important birthday calendar).

Perl uses –e $filevar to test for the existence of the file named by the scalar value in $filevar. If this file exists, the result is true; otherwise it is false. For example:

$name = "index.html";

if (-e $name) {

print "I see you already have a file named $name\n";

} else {

print "Perhaps you'd like to make a file called $name\n";

}

Page 69: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L02: The –x File Tests

To test whether the file opened as SOMEFILE is executable, you can use:

if (-x SOMEFILE) {

# file open on SOMEFILE is executable

}File Test Meaning

-r File or directory is readable

-w File or directory is writable

-x File or directory is executable

-o File or directory is owned by user

-e File or directory exists

-f Entry is a plain file

-d Entry is a directory

-T File is "text"

-B File is "binary"

Commonly used file tests:

Page 70: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 2, Lesson 03 (D2L03)

Creating and Using Subroutines (user-defined functions)

What Is a Subroutine? Return Values Subs with Arguments Using “require” Package Names About @INC

Page 71: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: What is a Subroutine?

We've already seen and used built-in functions, such as chomp, print, and so on. Now, let's take a look at functions that you define for yourself.

A user function, more commonly called a subroutine or just a sub, is defined in your Perl program using the keyword sub.

To call, use the ampersand followed by the subroutine name. The call can precede or follow the definition.

sub example {print “This is the simplest subroutine you will ever

see.”;}

example();

Page 72: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: Return Values

A subroutine is always part of some expression. The value of the subroutine invocation is called the return value. The return value of a subroutine is the value of the return statement or of the last expression evaluated in the subroutine.

For example, let's define this subroutine:

sub sum_of_a_and_b {return $a + $b;

}

Here's that subroutine in action:

$a = 3; $b = 4;$c = sum_of_a_and_b(); # $c gets 7$d = 3 * sum_of_a_and_b(); # $d gets 21

Page 73: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: Subs with Arguments

In the procedure call, any arguments (parameters) to be passed are placed in a list within parentheses.

They will be passed through a special array named @_

Perl procedures are call by reference. The local() keyword can be used to create any

variables that are local to the procedure.

Page 74: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: Procedures with Arguments (cont.)

sub example {local($arg1) = $_[0];local($arg2) = $_[1];local($arg3) = $_[2];print “$arg1 is a $arg2 $arg3!!\n”;

}

example(’Richard’, ’phenomenal’, ’teacher’);example(’This’, ’useless’, ’procedure’);

Output:Richard is a phenomenal teacher!!This is a useless procedure!!

Page 75: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: Using libraries

Libraries and modules are files which contain Perl code. The code can be subroutines, or other things like configuration information for scripts.

In its most basic form, a library file (which has a .pl extension) looks like this:

MyLibrary.pl:

sub { print "Hello, World!\n";}1;

To use this in your script, you'd require it in your script.

require "MyLibrary.pl";

Page 76: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: Using modules

In its most basic form, a module file (which has a .pm extension) looks like this:

MyModule.pm:

package MyModule;sub Greet{ print "Hello,World!\n";}1;

To use this in your script, you'd use it in your script.

#!/usr/bin/perl -wuse MyModule;MyModule::Greet();

Exercise:Write a Module ModAdd.pm that accepts 2 numbersand returns the sum. Write use.pl that uses it.

Page 77: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: Package Names

A package name is a way to manage a namespace, and a namespace is just a way to help you separate variables and functions into different "compartments".

A package name is conceptually similar to a directory name, and the variables in the package are like the files in that directory.

For example, you can have several files that have the same name, but if they live in different directories, they won't clash with each other.

As far as Perl modules are concerned, the package name is the module name. You've seen them before, and they look like this:

• MyModule::variable

This format makes it easy to remember that Astaire::Fred isn't Flintstone::Fred. Variables in different packages are different variables, even if they have the same names.

Page 78: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: About @INC

@INC is a special built-in array which contains the list of places to look for Perl scripts to be evaluated by the do FILENAME and require commands.

Page 79: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 2, Lesson 04 (D2L04)

Formatting Output “printf” and “sprintf” Formats

Page 80: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: “printf” and “sprintf”

printf and sprintf is used the same way like with their C/C++ counterparts.

Perl follows the C formatting convention:Flag Purpose

%% a percent sign

%c a character with the given number

%s a string

%d a signed integer, in decimal

%u an unsigned integer, in decimal

%o an unsigned integer, in octal

%x an unsigned integer, in hexadecimal

%e a floating-point number, in scientific notation

%f a floating-point number, in fixed decimal notation

%g a floating-point number, in %e or %f notation

Page 81: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: More “printf” and “sprintf”

Between the "%" and the format letter, you may specify a number of additional attributes controlling the interpretation of the format such as the precision and number of digits. Examples:printf '<%f>', 1; # prints "<1.000000>"

printf '<%.1f>', 1; # prints "<1.0>"

printf '<%.0f>', 1; # prints "<1>"

printf '<%e>', 10; # prints "<1.000000e+01"

printf '<%.1e>', 10; # prints "<1.0e+01>"

printf '<%g>', 1; # prints "<1>"

printf '<%.10g>', 1; # prints "<1>"

printf '<%g>', 100; # prints "<100>"

printf '<%.1g>', 100; # prints "<1e+02>"

printf '<%.2g>', 100.01; # prints "<1e+02>"

printf '<%.5g>', 100.01; # prints "<100.01>"

printf '<%.4g>', 100.01; # prints "<100>"

Page 82: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: Formats

Perl provides the notion of a simple report writing template, called a format. A format defines a constant part (the column headers, labels, fixed text, or whatever) and a variable part (the current data you're reporting).

Using a format consists of doing three things:1. Defining a format 1.2. Loading up the data to be printed into the variable portions

of the format (fields) 2.3. Invoking the format 3.

Page 83: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: Defining Formats

An example format definition: The first line contains the reserved word format, followed by the

format name and then an equal sign (=). The end of the template is indicated by a line consisting of a

single dot by itself.

format ADDRESSLABEL =

===============================

| @<<<<<<<<<<<<<<<<<<<<<<<<<< |

$name

| @<<<<<<<<<<<<<<<<<<<<<<<<<< |

$address

| @<<<<<<<<<<<<<<<<, @< @<<<< |

$city, $state, $zip

===============================.

Page 84: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D2L03: Invoking Formats

You can invoke the format you just created like so:

open(ADDRESSLABEL,">labels-to-print") || die "can't create";

open(ADDRESSES,"addresses") || die "cannot open addresses";

while (<ADDRESSES>) {

chomp; # remove newline

($name,$address,$city,$state,$zip) = split(/:/);

# load up the global variables

write (ADDRESSLABEL); # send the output

}

Page 85: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 3, Lesson 01 (D3L01)

Manipulating Files and Directories Removing Files Renaming Files Linking Making and Removing Directories Modifying Permissions

Page 86: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L01: Removing Files

The Perl unlink function (named for the POSIX system call) deletes one name for a file (which could possibly have other names).

This is exactly what the UNIX rm command does. Because a file typically has just one name (unless you've created hard links), for the most part, you can think of removing a name as removing the file.

unlink ("fred"); # say goodbye to fred

print "what file do you want to delete? ";

chomp($name = <STDIN>);

unlink ($name);

The unlink function can take a list of names to be unlinked as well:

unlink ("cowbird","starling"); # kill two birds

unlink <*.o>; # just like "rm *.o" in the shell

Page 87: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L01: Renaming Files

In the UNIX shell, you change the name of a file with the mv command. With Perl, the same operation is denoted with rename($old,$new). Here's how to change the file named fred into barney:

rename("fred","barney") || die "Can't rename fred to barney: $!";

Page 88: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L01: Linking

As if one name for a file weren't enough, sometimes you want to have two, three, or a dozen names for the same file. This operation of creating alternate names for a file is called linking.

The two major forms of linking are hard links and symbolic links (also called symlinks or soft links).The UNIX ln command creates hard links.

On Microsoft Windows and MacOS systems, shortcuts are the closest equivalents to UNIX links.

Create a hard link from the file fred (which must exist) to bigdumbguy:

link("fred","bigdumbguy") || die "cannot link fred to bigdumbguy";

To create a symbolic link from barney to neighbor (so that a reference to neighbor is actually a reference to barney), you'd use something like this:

symlink("barney","neighbor") ||

die "cannot symlink to neighbor";

Page 89: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L01: Making and Removing Directories

The UNIX command mkdir command, which makes directories that hold other filenames and other directories.

Perl's equivalent is the mkdir function, which takes a name for a new directory and a mode that will affect the permissions of the created directory. Here’s how to create a directory called gravelpit:

mkdir("gravelpit",0755) || die "cannot mkdir gravelpit: $!";

The The UNIX rmdir command removes empty directories; you'll find a Perl equivalent with the same name. Here's how to make Fred unemployed:

rmdir("gravelpit") || die "cannot rmdir gravelpit: $!";

Page 90: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L01: Modifying Permissions

The permissions on a file or directory define who can do what to that file or directory.

Under UNIX, the typical way to change permissions on a file is with the chmod command.

Similarly, Perl changes permissions with the chmod function.

chmod(0666,"fred","barney");

Page 91: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L01: Exercises

1. Write a program that works like rm, deleting the files given as command-line arguments when the program is invoked. (You don't need to handle any options of rm.) Be careful to test this program in a mostly empty directory so you don't accidentally delete useful stuff! Remember that the command-line arguments are available in the @ARGV array when the program starts.

1. Write a program that works like mv, renaming the first command-line argument to the second command-line argument. (You don't need to handle any options of mv, or more than two arguments.) You may wish to consider how to handle the rename when the destination is a directory.

1. Write a program that works like ln, creating a hard link from the first command-line argument to the second. (You don't need to handle any options of ln, or more than two arguments.)

1. If you have symlinks, modify the program from the previous exercise to handle an optional –s switch.

1. If you have symlinks, write a program that looks for all symlinked files in the current directory and prints out their name and symlinked value similar to the way ls -l does it (name -> value). Create some symlinks in the current directory and test it out.

Page 92: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 3, Lesson 02 (D3L02)

Special Variables Using @ENV Using $ARGV

Page 93: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L02Special Variables

$_ -- The default input and pattern-searching space. @ARGV -- (argument vector) contains an array of the

command line arguments %ENV -- associative array containing environment

variables STDIN/STDOUT/STDERR -- special predefined

filehandles

Page 94: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L02: Using @ENV

Environment variables are used by the operating system to store bits of information that are needed to run the computer.

They are called environment variables because you rarely need to use them and because they simply remain in the background-just another part of the overall computing environment of your system.

The example below will list out all your environment variables:

foreach $key (keys(%ENV)) {

printf("$key : $ENV{$key}\n");

}

Page 95: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L02: Using $ARGV

With Perl, command-line arguments are stored in the array named @ARGV.

$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.

$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.

Here's a simple program that prints the number of command-line arguments it's given, and the values of the arguments:

$numArgs = $#ARGV + 1; print "thanks, you gave me $numArgs command-line arguments.\n"; foreach $argnum (0 .. $#ARGV) {

print "$ARGV[$argnum]\n"; }

Page 96: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 3, Lesson 03 (D3L03)

Text Processing Regular Expressions Pattern Matching Split/Join Operators

Page 97: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L03: Regular Expressions

A pattern that can be used to describe a set of strings.

Used in perl’s pattern matching and substitution commands.

Also used in vi, emacs, sed, egrep. Inside a regexp, certain character sequences have

special meanings...

Page 98: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L03: Regexps (cont.)

. Matches any character but \n[a-z0-9] Matches any single character in set[^a-z0-9] Matches any single character not in set\s Matches a whitespace char (sp/tab/nl)\S Matches a non-whitespace char\d Matches a digit (same as [0-9])\w Matches alphanumeric char [a-zA-Z0-9_]\n Matches a newline\t Matches a tab(abc) Remembers the match for later reference

(stored in $1, $2, $3, etc...)

Page 99: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L03: Regexps (cont.)

x? Matches 0 or 1 x’sx* Matches 0 or more x’sx+ Matches 1 or more x’sx{m,n} Matches between m and n x’s

abc Matches all of a, b, and c in orderfee|fie|foe Matches one of fee, fie, or foe

\b Matches a word boundary^ Anchors to beginning of line/string$ Anchors to end of a line or string

Page 100: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L03: Regexp Examples

Oh s.*t.Oh say can you see by the dawn’s early light.

(\d+) (\w+) (\d+) (\d+):(\d+):(\d+)1 Apr 91 12:34:56

[0-9]*\.[0-9]+5.3333

-?(([0-9]+)|([0-9]*\.[0-9]+))-76

-?(([0-9]+)|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?)5.7e-33

Page 101: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L03: Pattern Matching

The =~ operator is used to bind a pattern match to a string (other than $_)

MATCH: $a =~ /pat/– evaluates to TRUE if $a contains pat– usually used within an if statement

SUBSTITUTION: $a =~ s/pat/repl/[g][i]– replaces occurrences of pat with repl in $a– g option for replacing all occurrences of pat– i option for case-insensitive matching

TRANSLATION: $a =~ tr/a-z/A-Z/– translate all lower case alphabets to uppercase– return value is number of characters replaced

Page 102: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L03: Matching Examples

while(<STDIN>){ if($_=~/abc/){ print “Matched\n”; } }}

while(<STDIN>){ $_=~ s/abc/def/g; print “$_\n”;}

Exercise:Write a program to convert all chars to uppercase.

Page 103: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L03: More matching examples

$string =~ s/\bgreen\b/mauve/g;green must be a separate word to match

$string =~ s/$foo/$bar/g;substituting one variable for another

$string =~ s/([^c])ei/$1ie/g;i before e except after c

$string =~ s/(\S+)\s+(\S+)/$2 $1/;swaps the first two words of $string

replace “/z1263a” from line “/net/gato/usr3/projects/z1263a” with nothing, assuming the line is $_s/\/\w+$//g ;

Page 104: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L03: Splitting Lines into Tokens

The split function separates a string into tokens delimited by the first argument. The result is stored in an array.

The join function does the opposite.

$scores = “18 9 3 8 1 18 4”;@result = split(’ ’, $scores);foreach $i (0 .. $#result) { print “score $i = $result[$i]\n”;}

$new_scores = join(’ ’, @result);

Note: $scores is the same as $new_scores.

Page 105: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 3, Lesson 04 (D3L04)

Special Variables Using @ENV Using $ARGV

Page 106: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L04: References

A reference is a scalar value that refers to an entire array or an entire hash (or to just about anything else.)

If you have a reference to an array, you can recover the entire array from it. If you have a reference to a hash, you can recover the entire hash.

If you put a \ in front of a variable, you get a reference to that variable.

$aref = \@array; # $aref now holds a reference to @array $href = \%hash; # $href now holds a reference to %hash

Once the reference is stored in a variable like $aref or $href, you can copy it or store it just the same as any other scalar value:

$xy = $aref; # $xy now holds a reference to @array$p[3] = $href; # $p[3] now holds a reference to %hash$z = $p[3]; # $z now holds a reference to %hash

Page 107: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L04: References

Working with arrays the normal way versus the reference way:

Normal Reference Comment@a @{$aref} An arrayreverse @a reverse @{$aref} Reverse the array$a[3] ${$aref}[3] An element of the array$a[3] = 17; ${$aref}[3] = 17 Assigning an element

Working with hashes the normal way versus the reference way:Normal Reference Comment%h %{$href} A hashkeys %h keys %{$href} Get the keys from the

hash$h{'red'} ${$href}{'red'} An element of the hash$h{'red'} = 17

${$href}{'red'} = 17

Assigning an element

Page 108: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L04: Multidimensional Lists

[1, 2, 3] makes an anonymous array containing (1, 2, 3), and gives you a reference to that array

Now think about:

@a = ( [1, 2, 3], [4, 5, 6], [7, 8, 9] );

Reference to anonymous arrays

@a is an array with three elements, and each one is a reference to another array.

$a[1] is one of these references. It refers to an array, the array containing (4, 5, 6), and because it is a reference to an array

You can write $a[ROW]->[COLUMN] to get or set the element in any row and any column of the array. You can even ignore the -> to make it even more concise: $a[ROW][COLUMN]

Page 109: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D3L04: Exercise

1. Write a program to print out the following 2-D array:

@a = ( [1, 2, 3], [4, 5, 6], [7, 8, 9] );

2. Modify the above program to input your own numbers input the 2-D array. Use modular programming.

Reference to anonymous arrays

Page 110: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 4, Lesson 01 (D4L01)

Special Variables Object Oriented Programming in Perl

Page 111: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D4L01: OOP in Perl (Intro)

Objects, objects, objects! The programming world seems to be going ``object-oriented'‘ and Perl is not an exception.

However, unlike some other popular programming languages, you can write Perl code using objects, or avoid them entirely.

A Perl ``object'' is nothing more than a reference to a data structure.

However, the reference has been ``blessed'' into a particular package, making this package the ``class'' of the object.

The purpose of the blessing is to allow ``methods'' to be called later on this object. A method is nothing more than an ordinary subroutine, but the subroutine is found within the package from which the object was blessed.

Page 112: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D4L01: OOP in Perl

Let's take a look at a simple example. I'm going to create an object class called Car. Within it, I'm going to put a method that creates new cars for me to use, called ``new''. The invocation looks like this: $myCar = new Car;

Now, in order for this to work, we'll need to have a subroutine called ``new'' in the package Car. It'll look like this:sub Car::new {

my $class = shift;

my $self = {};

bless $self, $class;

$self->{passengers} = {};

$self;

}

Page 113: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 4, Lesson 02 (D4L02)

TCP/IP Client-Server Programming Creating the server Creating the client

Page 114: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D4L02: Introduction

Networking is now used daily by organizations and individuals from every walk of life.

They use networking to exchange email, schedule meetings, manage distributed databases, access company information, grab weather reports, pull down today's news, chat with someone in a different hemisphere, or advertise their company on the Web.

These diverse applications all share one thing in common: they use TCP networking, the fundamental protocol that links the Net together.

Don't let fancy words like "client-server programming“ put you off. When you see the word "client," think "caller"; when you see the word "server," think "responder." If you ring someone up on the telephone, you are the client. Whoever picks up the phone at the other end is the server.

Page 115: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D4L02: Network Functions

Programmers with a background in C programming may be familiar with sockets.

A socket is the interface to the network in the same sense that a filehandle is the interface to files in the filesystem. In fact, for the simple stream-based clients we're going to demonstrate below, you can use a socket handle just as you would a filehandle.

All you need is the IO::Socket object and you are set to create client-server applications in Perl.

You can read from the socket, write to it, or both. That's because a socket is a special kind of bidirectional filehandle representing a network connection. Unlike normal files created via open, sockets are created using the low-level socket function.

The Perl functions getservbyname and getservbyport can be used to look up a service name given its port number, or vice versa. (refer to textbook for a list of common ports)

Page 116: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D4L02: The Server

#!/usr/bin/perl -w -s

##########

# server

##########

use strict;

use IO::Socket;

my $localport = 3003; # Socket that this server listens on.

print STDOUT "SERVER: starting serverDemo \n";

my $sockListen = IO::Socket::INET->new( Proto => 'tcp',

LocalPort => $localport,

Listen => 5,

Reuse => 1,

)

or die "SERVER: Couldn't listen at port $localport; $@";

Page 117: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D4L02: The Server

print STDOUT "SERVER: accepting clients at port $localport. \n";

$sockListen->autoflush(1); # write everything out immediately.

$sockListen->blocking(1); # wait for the other end when accepting

# The INET->accept() call, below, waits (i.e. "blocks") for a new connection.

# Once we get one, we deal with it, close it, and wait for the next.

# (This simple server model assumes we can deal with requests quickly.)

while ( my $sockClient = $sockListen->accept ) {

$sockClient->autoflush(1); # write everything out immediately.

$sockClient->blocking(1); # wait for the other end when reading

Page 118: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D4L02: The Server# send out initial greeting

my $toClient = "Hi. Server time is " . scalar localtime();

print STDOUT "SERVER: sending '$toClient'\n";

$sockClient->print($toClient."\n");

$sockClient->blocking(1); # wait for the other end when reading

# read and echo any lines from the client

while ( my $fromClient = $sockClient->getline ) {

chomp($fromClient);

print STDOUT "SERVER: receieved '$fromClient'\n"; # output it

}

# close this connection down

print STDOUT "SERVER: client closed connection.\n";

close($sockClient);

}

# We never get here, so the sever can only be shut down manually.

Page 119: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D4L02: The Client#!/usr/bin/perl -w -s

##########

# client

##########

use strict;

use IO::Socket;

our $host = 'localhost' unless $host;

our $port = 3003 unless $port; # must match server's

our $pause= 0 unless $pause; # delay after connect

print STDOUT "CLIENT: starting clientDemo. \n";

Page 120: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D4L02: The Clientmy $sock = IO::Socket::INET->new( Proto => 'tcp',

PeerAddr => $host,

PeerPort => $port,

)

or die "CLIENT: Failed to connect (host='$host',port='$port'); $@";

print STDOUT "CLIENT: connected \n";

$sock->autoflush(1); # make sure we're sending stuff right out

$sock->blocking(1); # make sure we wait (block) for other end on reads

my $message = "Hello. Client time is " . scalar localtime();

print STDOUT "CLIENT: sending '$message' \n";

$sock->print($message."\n"); # write a line to the server

chomp(my $response = $sock->getline); # read a line from the server

print STDOUT "CLIENT: received '$response'\n";

print STDOUT "CLIENT: closing connection.\n";

close($sock);

exit;

Page 121: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D4: Miscellaneous Odds/Ends

System Command– used to run unix commands– ex: system ”rm -rf *”

perldoc– Get online help on Perl commands– perldoc –f <function>

perldoc [options] PageName|ModuleName|ProgramName...

perldoc [options] -f BuiltinFunction

perldoc [options] -q FAQRegex

Page 122: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 5, Lesson 01 (D5L01)

CGI Programming Introduction CGI.pm How does it work? What is a query string?

Page 123: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D5L01: Introduction

Many of the more interesting web pages include some sort of entry form.

You supply input to this form and click on a button or picture. This fires up a program at the web server that examines your

input and generates new output. Sometimes this server side program is commonly known as a

CGI program. CGI : Common Gateway Interface It is a “Common Gateway” (standard way) to allow web pages to

interface (connect) to other systems such as a database or another program on the server.

Page 124: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D5L01: CGI.pm

Written by Lincoln Stein, author of the acclaimed book How to Setup and Maintain Your Web Site

Makes writing CGI programs in Perl a breeze. Starting with the 5.004 release, the standard Perl

distribution includes CGI.pm module.

Page 125: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D5L01:How does it work?

Relationships between a web browser, web server, and CGI program.

Page 126: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

D5L01:What is a query string?

A query string consists of one or more name=value pairs; each name is the name of a text input field, and each value is the corresponding input you provided.

So the URL to which the browser submits your form input looks something like this (where the query string is everything after the question mark):http://www.SOMEWHERE.org/cgi-bin/some_cgi_prog?flavor=vanilla&size=double

When the web server (www.SOMEWHERE.org in this case) receives the URL from your browser, it invokes the CGI program, passing the name=value pairs to the program as arguments.

The program then does whatever it does, and (usually) returns HTML code to the server, which in turn downloads it to the browser for display to you.

Page 127: Welcome to Perl Programming by Paul Chin Jonathan Ong INTI Industrial Training Centre

Day 5, Lesson 02 (D5L02)

Your first CGI Program#!/usr/bin/perl -w

# howdy--the easiest of CGI programs

print <<END_of_Multiline_Text;

Content-type: text/html

<HTML>

<HEAD>

<TITLE>Hello World</TITLE>

</HEAD>

<BODY>

<H1>Greetings, Terrans!</H1>

</BODY>

</HTML>

END_of_Multiline_Text