0% found this document useful (0 votes)
52 views

Perl Training

Uploaded by

abhinav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Perl Training

Uploaded by

abhinav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Introduction To Perl Programming

1 Introduction

1.1 What is Perl?


• Perl = “Practical Extraction and Report Language”
• Perl is optimized for scanning arbitrary text files,
extracting information from those text files, and printing
reports based on that information.
• According to its author, Larry Wall, “ the language is
intended to be practical (easy to use, efficient,
complete) rather than beautiful (tiny, elegant, minimal).
It combines some of the best features of C, sed/awk,
and UNIX shell. ”

1.2 Advantages of Perl


• Speed and Efficiency
Perl compiles a program before executing it
It is usually run faster than sed/awk scripts

• Regular Expressions
Unlike shell and C, Perl has built-in regular expression
A regex is a way of describing a set of strings without
having to list all the strings in your set

• Automatic Error Recovery


Perl makes some assumptions to recover from errors
open() or close() on empty file handle do not cause
crash

1
Introduction To Perl Programming

1.3 Perl Basics


1.3.1General
• Perl program is executed in “top-down” manner
• No main() function
• Unlike the shell, but similar to C, Perl programs (or
script files) are freely formatted

1.3.2 Interpreter
• The first line contains the character sequence #!
followed by the full pathname of the Perl interpreter

#!/usr/intel/bin/perl

1.3.3 Comments
• Uses # for comments

# This is a comment line

All text after # will be ignored, except first line which


Note start from #!
Note

1.3.4 End of Statement


• Each statement end in semi-colon ;

print("hello,world\n");

2
Introduction To Perl Programming

LAB 1
1. Using a text editor such as vi or emacs, input the line of
statement below and then save the file as hello.pl
print("hello,world\n");

At Unix shell prompt, run


$> perl hello.pl

2. Edit the file hello.pl again, using the previous file.


Append the statement below at the first line of the file,
then save it.

#!/usr/intel/bin/perl

At Unix shell prompt, run


$> hello.pl

Note hello.pl must be in executable mode (+x)


Note

3
Introduction To Perl Programming

2 Literals

2.1 Numbers
• Numerical values can be specified in 4 types
▪ Decimal –> Decimal number is base 10
Example: 20
▪ Hexadecimal – > Data prefixed with 0x is base 16
Example: 0x14
▪ Octal –> Data prefixed with a single 0 is base 8
Example: 024
▪ Scientific –> Values in the form of xE+y
Example: 2E1

2.2 Strings
• Strings are stored in either single or double quotes

$x = "hello";
$x = hello;

• The difference between them is that variables within


double quotes are being evaluated

$x = "hello";
print "$x,world\n"; # display: hello,world
print $x,world\n; # display: $x,world\n

Note The single quote is  (apostrophes) not ` (backticks)


Note

4
Introduction To Perl Programming

2.3 Math Operators


• List of current math operators available

++ Increment Operator
-- Decrement Operator
** Exponentiation
% Modulus (3%2 returns 1, the remainder)
* / Multiplication and Division
+ - Addition and Subtraction

5
Introduction To Perl Programming

3 Scalar Data

3.1 General
• All references to scalar variables (both assigning and
retrieving) are prefixed with the $ character
• Can be a number, string of characters or boolean
• Default to undef, null string or 0

3.2 Assigning Values


• Assigning values to scalar variables uses the =
operator, as in:

$name = "Intel Malaysia";

3.3 Retrieving Values


• The scalar variables (once assigned) can then be used
in other places

print $name;

3.4 The Special $_ Variable


• Default for many operations
• Default input and pattern searching
• Used to hold the current line

6
Introduction To Perl Programming

3.5 chop() Operator


• Takes in a single argument and removes the last
character from the argument
• Useful since perl doesn’t automatically discard newlines

$scalar = "12345";
chop($scalar); # scalar is 1234

7
Introduction To Perl Programming

4 Basic I/O

4.1 STDIN
• Read in the next line from standard input

print "Enter your name: ";


$name = <STDIN>;

$name = chop($name);
print "Hello $name, $lastchar";

chop($name);
print "Hello $name";

chop($name);
print "Hello $name";

Why we left the carriage-return at the third line?


Question

4.2 STDIN Shortcut


• The default filehandle inside the diamond operator <> is
STDIN, there for both statements below are identical

$name = <STDIN>;
$name = <>;

4.3 STDOUT and STDERR


• Filehandle for standard output and error.

8
Introduction To Perl Programming

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

Expected output:

$> lab2.pl
Enter string: test
Enter times: 3
test
test
test

9
Introduction To Perl Programming

5 Arrays

5.1 Definition
• Arrays are groups of scalar variables, with each
member indexed by a number
• Arrays can have any number of elements
• Elements can store anything from a number, a string to
a pointer to another array
• Denoted by initial character “ @“

@name = (martin,alan,dave,andy);
@number = (1, 2, 3, 4, 5, 6);
@newname = (mike,@name);# newname is (mike,
#martin, alan, dave,
#andy)

• Array elements are referenced by $array[n], where n is


an integer starts from zero

@junk = (2, 4, 6, 8);


$junk[0]; # referring to 2
$junk[1]; # referring to 4
$junk[2]; # referring to 6
$junk[3]; # referring to 8

What is $#array and $?


Question

10
Introduction To Perl Programming

5.2 push() and pop() operators


• An array can acts like a stack
• push() add a new member to an array at the end
• pop() will take the last member of an array off

push(ARRAY,LIST)
appends LIST to the end of ARRAY
pop(ARRAY)
removes the last element of ARRAY, returns element pop off

Examples:

@first = (1, 2, 3);


@second = (4, 5, 6);
push(@first, @second); # @first is now 1, 2, 3,
# 4, 5, 6
$last = pop(@first); #last is now 6

What is @first now?


Question

11
Introduction To Perl Programming

5.3 shift() and unshift() operators


• Use shift() and unshift() to add or remove a member
from the beginning of an array
• shift(ARRAY) removes the first element of an array,
returns the element shifted
• unshift(ARRAY,LIST) prepends list to the beginning of the
array

@array = (1, 2, 3, 4);


$first = shift(@array); # $first is 1 and @array
# is (2, 3, 4)
unshift(@array,$first); # $first is 1 and @array
# is (1, 2, 3, 4)

5.4 reverse() operator


• Reverse the order of a list

@array = (1, 2, 3, 4, 5);


@reverseArray = reverse(@array);
#reverseArray is #(5, 4, 3, 2, 1)

5.5 sort() operator


• Sorts elements as single strings in ASCII order

@name = (martin,alan,dave,andy);
@sortName = sort(@name);
# @sortName is alan, andy, dave, martin

How about number? Will it be sorted base of number


Question or ASCII?

12
Introduction To Perl Programming

LAB 3
1. Write a program that read 3 different strings and store
in into an array list.
(Hint: use <STDIN>)
print @ARRAY;
print “@ARRAY”;
print @ARRAY.””;
print $#ARRAY;
print $”;

2. Using the existing program from Question 1, display


random string from the list.

Note:
srand; #initialize the random generator
rand(@array); #return a random value between 0 and
#one less than the length of @array

13
Introduction To Perl Programming

6 Control Structures

6.1 if-then Statement


• Sequences of statements have to be enclosed with
curly braces { }
• Test expression are evaluated for true-ness
• Type I

if (test_expression) {
statements;
...
}

• Type II

if (test_expression) {
statements;
...
} else {
statements;
...
}

• Type III

if (test_expression) {
statement;
...
} elsif (test_expression) {
statement;
...
} else {
statement;
...
}

14
Introduction To Perl Programming

6.2 Loop Statements


6.2.1 while Statement
• The block of code between braces is repeated as long
as the comparison is true

while (test_expression) {
statement;
...
}

6.2.2 for Statement

for (initial_exp; test_exp; incre_exp) {


statement;
...
}

6.2.3 foreach Statement

foreach $var (@list) {


statement;
...
}

15
Introduction To Perl Programming

6.2 Loop Controls


6.2.1 last Statement
• Breaks out of the innermost enclosing loop and
resumes statement execution immediately following the
loop

while (test_expression) {
statement1;
if (condition) {
statement2;
last;
}
statement3;
}
# last statement reach here

6.2.2 next Statement


• Doesn’t exit of the loop but will skip the rest of
statements in the loop

while (test_expression) {
statement1;
if (condition) {
statement2;
next;
}
statement3;
# next statement reach here
}

16
Introduction To Perl Programming

6.2.3 redo Statement


• Doesn’t exit the loop but jumps to the beginning of the
loop without revaluating the loop test expression

while (test_expression) {
# redo statement come here
statement1;
if (condition) {
statement2;
redo;
}
statement3;
}

6.3 Nested Loop


• We can specify which loop a last, next or redo should
refer by using LABEL

LABEL: while (test_expression) {


for ($i=1;$i<=10; $i++) {
if (condition) {
last LABEL;
}
} # default last reach here
statement;
} # enforce last reach here

17
Introduction To Perl Programming

LAB 4
1. Write a program that prints a table of numbers, x, and
their squares, x 2, from 0 to 16 using while loop.

2. Write the program in Question 1 using for loop.

3. Write the program in Question 1 using a foreach loop


and all the values are in an array.

18
Introduction To Perl Programming

7 Associative Arrays

7.1 Introduction
• Associative arrays also called hash
• Very similar to array, except that instead of being
indexed by a number with a particular order, they are
indexed by a string
• Denoted by “%”
• Each element of the array is a separate scalar variable,
accessed by the scalar index called the key

%hash = ();

$hash{"a"}{fruit} = "apple";
$hash{"a"}{people} = "boy";

7.2 keys() Operator


• keys(ASSOC_ARRAY) gives a list of the current keys in the
associative array

foreach $key (keys %hash) {


print "$key \n";
} # this will print "a" and "b"

19
Introduction To Perl Programming

7.3 values() Operator


• values(ASSOC_ARRAY) gives a list of current values in the
associative array

foreach $value (values %hash) {


print "$value \n";
} # this will print "apple" and "boy"

7.4 each() Operator


• each(ASSOC_ARRAY) returns a key-value pair as a two
element list

while (($key, $value) = each %hash) {


print "$key for $value\n";
} # print "a for apple" , "b for boy"

7.5 delete() Operator


• delete $assoc_array{$key} removes a key-value pair
from associative array

delete $hash{"a"}; # remove "a" from %hash

20
Introduction To Perl Programming

8 Basic File I/O

8.1 File Handle


• Filehandle is an I/O connection between the perl
process and the outside world
• Perl provides 3 filehandles STDIN, STDOUT and STDERR as
mentioned earlier
• Filehandle can open files for reading, writing data into
perl program

open (FILEHANDLE, "filename"); #read file


open (FILEHANDLE, ">>filename"); #write file
open (PROCESSHANDLE, "ls -l");
#input from process

• Closed a file handle with close() operator

close (FILEHANDLE);

8.2 Directory Handle


• Directory handle establish a read-only connection
between perl and a directory

opendir (DIRHANDLE, "directory"); # open


#directory for processing
readdir (DIRHANDLE); # return a lists of entries
closedir (DIRHANDLE); # close the handle

21
Introduction To Perl Programming

• die() operator
used to display a list and exits the
program when a error occurred

open (FILE, "filename") || die "Can’t open


file\n";

22
Introduction To Perl Programming

LAB 5
1. Write a program that reads a series of words with one
word per line until end of file. The print a summary of
how many times each word was seen.
(Hint: use word as key, counter as value)

23
Introduction To Perl Programming

9 Directory Access

9.1 Basic
• To change the current directory of a process
chdir ("/etc");# change to the /etc directory
chdir (); # change to home directory

• Perl also support argument expansion


@array = </etc/rc*>; #return all matching
#files list

• Scalar context returns number of matching entries


• Array context returns list of matching entries

24
Introduction To Perl Programming

10 File & Dir Manipulation

10.1 Removing Files


• Removing files in perl is done by using ‘unlink’
unlink (LIST);
unlink ("filename");
unlink ("filename1","filename2");
unlink (<filename*>);

10.2 Moving Files


• Moving files in perl is done by using ‘rename’
rename (old_name, new_name);
rename ("a", "/usr/bin/a");

10.3 Making and Removing Directories


• Making directory in perl is done by using ‘mkdir’
mkdir (dirname, mode);
mkdir ("test", 0755); # create a directory
# with read & execute permissions

• Removing directory in perl is done by using ‘rmdir’


rmdir (dirname);
rmdir ("test"); # remove the directory

25
Introduction To Perl Programming

10.4 Creating Links


• Creating hardlink in perl is done by using ‘link’

link (FILE, LINK);


link ("test", "t");

• To create a symbolic link


symlink (EXPR, LINK);
symlink ("/dir/file", "symbol");

10.5 Modifying Permissions, Ownership &


Timestamps
• Changing permissions
chmod (PERMISSION, LIST);
chmod (0755, "file1", "file2");

• Changing ownership using ‘chown’ command, the uid


and gid must be numerical
chown (UID, GID, LIST);
chown (1234, 56, "file1");

• The ‘utime’ function can change the access &


modification times on a list of files (similar to touch)

utime (ATIME, MTIME, LIST);

$now = time;
utime ($now, $now, "file1"); # touch file1

26
Introduction To Perl Programming

LAB 6
1. Write a program that works like ‘mv’, renaming the first
command-line argument to the second command-line
argument.
(Hint: use @ARGV to get argument)

27
Introduction To Perl Programming

11 Regular Expressions

11.1 Definition
• Regex is a pattern to be matched against a string
• $_ is matched by default
• =~ used to match variable strings other than $_

• //used to as standard delimiters to contain pattern to


be matched

11.2 Patterns
• Any single character matches itself
/bob/ # matches word "bob"
• The "." matches any character
/b.b/ # matches word "bxb", "beb"…
• The "*" matches 0 or more of the preceeding character
/b.*b/ # matches word "bb", "bxb", "baaab" …
• The [ ] matches a single character within the bracket
/[acz098]/ # matches any single digit

Regular expression also provide assertion that match


a pre-defined group of string. For example, /\d/
Note matches any single digit or equivalents to /[0-9]/.
Note
Please refer to regex guide for details.

28
Introduction To Perl Programming

11.3 Usage
• Search and replace

s/PATTERNS/REPLACEMENT/;
s/a/b; # match a and replace it with b

• Example:
$_ = "thiiiiiiiis x a test";
s/i+/i/; # $_ = "this x a test"
s/x/is/; # $_ = "this is a test"

11.4 split() Operator


• split(/PATTERN/, EXPR, LIMIT) separates a string into an
array of strings. PATTERN specifies the delimiter where
the string will split (whitespace is the default). EXPR is
the string to be separated ( $_ is the default). LIMIT is
optional. If LIMIT is specified, then split() splits the
string into the number of strings the LIMIT specifies.

$_ = "red:blue:green";
($color1,$color2,$color3) = split(/:/);
($color1,$rest) = split(/:/,$_,2);
# $rest = blue:green

29
Introduction To Perl Programming

LAB 7
1. Write a program that read the file /etc/passwd, printing
the login name and real name of each user.
(Hint: use split to break up the line up into fields, use
s/// to get rid of the parts of the comment field that are
after the first comma.)

30
Introduction To Perl Programming

12 Functions

12.1 Definition
• Functions (also called subroutines) are logical sections
of code that can be called repeatedly
• A subroutine is defined using the sub keyword, as in

sub subroutine_name {
statement1;
...
}

• A subroutine can be called using "&" (version 4) like


&subroutine_name(argument,...);

• Subroutines can be defined anywhere in a program


• Subroutines can invoke other subroutines
• Arguments are stored in the @_ array
• Subroutines use return command to return a value, if
no return value specified, Perl returns the value from
the last statement executed

sub twice
{
($x) = @_;
return ($x * 2);
}

$val = &twice(7); # $val = 14

31
Introduction To Perl Programming

• By default, variables in a subroutine are global


• Local variables can be declared for subroutines using
the local() operator

sub square
{
local($x);
($x) = @_;
return ($x * $x);
}

$val = &square(20); # $val = 400

32
Introduction To Perl Programming

LAB 8
1. Write a subroutine that calculate the factorial function,
x! , in math. factor(5) = 5 x 4 x 3 x 2 x 1 = 120;
(Hint: Think recursively…)

33

You might also like