Вы находитесь на странице: 1из 97

Learning and Knowledge Education India IBM India Pvt. Ltd.

Perl Scripting

Day 2 session

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Session content
Day two: Module 01: Pattern matching with Regular Expressions Module 02: References Module 03: Modules and packages Module 04: Basics of Object Orientation

Module 05: Perl Documentation


Module 06: Overview about CPAN

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module 1: Pattern matching with Regular Expressions

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module objectives
At the completion of this module, you should be able to: Define Regular Expression Discuss how to use the different parts of Regular Expression such as:
Character classes Alternative match patterns Quantifiers Assertions Backreferences Regular Expression extensions

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Regular Expressions
Regular Expressions are meta-characters that have special meaning to Perl and that could be used to match patterns in a string.

The parts of Regular Expression can be made up of the following:


Characters Character classes Alternative match patterns

Quantifiers
Assertions Backreferences Regular Expression extensions

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Characters

Char
^ $ . * + ?

Meaning
It matches pattern at the beginning of the string It matches pattern at the end of the string The dot character matches any single character It matches zero or more occurrence of the preceding character It matches one or more occurrence of the preceding character The question mark character matches zero or one occurrence of the preceding character

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Characters (continued)

Char
| () []

Meaning
It matches either of the patterns separated by this alternator character Parenthesis denotes grouping; "storing" Brackets denote Character class

{}
\

Braces denote Repetition modifier


Backslash denote quote or special

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Characters (continued)
The . (dot) character matches any character except a newline character. For example, we can substitute an asterisk (*) for all the characters in a string, where we make the substitution operation global with the g modifier.

Example:

$str=Now is the time.; $str =~ s/./*/g; print $str; Output: ****************

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Characters (continued)
To match a . (dot) character literally, we can precede the . character with a backslash (\) character which is also known as escape character.
Example:

$line=.Much ado about nothing;


print A sentence shouldnt start with a period if ($line =~ /^\./); Output: A sentence shouldnt start with a period

Explanation of code: The modifier for if statement is used; as we want to check if the string starts with a Period character. Also, we do not want the character dot (.) to be interpreted as a meta-character, we precede it with a \ to remove special meaning; we precede this pattern with a ^ symbol to match pattern at the beginning of string.

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Characters (continued)
In the following example, we are removing all comments from a C program:
while(<INFILE>) {

s|\/\*.*\*\/||g;
} Result: All comments are removed from the c Program file

Explanation of code: The while loop reads line by line from the c program file, which needs to be opened in input mode. The s modifier does substitution; the string specified within first pair of | characters is the string to be replaced; we want to match /* <any text> */; but, as / and * are meta-characters, we remove special meaning of these characters by preceding with a \ char.; we substitute this string with NULL.

10

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Character Classes


We can group characters into a character class, and that class will match any one character inside it.

We enclose character class in square brackets, [ and ]. We can specify a range of characters by using character or a list of characters also. The following example illustrates character class:
$text=Heres the text.; Print Yes, we got vowels\n if ($text =~ /[aeiou]/); Output: Yes, we got vowels

Explanation of code: In the above example, expression of if condition checks for existence of vowel In the scalar $text.

11

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Alternative Match Patterns


We can specify a series of alternatives for a pattern using | to separate them. The following example illustrates character class:

While (<STDIN>) { if (/^(exit|quit|stop/)$) { exit; }

}
Result: When user types exit or quit or stop, then script terminates

Explanation of code:
It keeps accepting input lines from the user, and when user types a line that contains only either exit or quit or stop, then the script terminates.

12

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Quantifiers


We can use quantifiers to specify that a character must match a specific number of times. The following example illustrates a quantifier:
$text=Hello from Peeeeeeeeerl.; $text =~ s/e+/e/g;

Print $text;
Output: Hello from Perl.

Explanation of code:

In the above code, the + quantifier is used to match and replace one or more occurrences of the letter e.

13

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Assertions


We use assertions, also called anchors, to match certain conditions in a string, not actual data. The following are valid Perl assertions:

\b It matches a word boundary \B It matches a non-word boundary \w It matches a word character \W It matches a non-word character \d It matches a digit character

\D it matches a non-digit character


\s it matches a white-space character \S It matches a non white-space character

14

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Assertions (continued)


One of the most commonly used assertions is \b, which matches word boundaries. This next example shows how we match a word, the first word in the text, using word boundaries.
$text = here is some text.; $text =~ s/\b\w+\b/There/;

print $text;
Output: There is some text.

Explanation of code:
In the above example, the substitute modifier matches first sequence of word characters, and replaces that with the word There.

15

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Backreferences


In creating Backreferences that refer to previous matches, we need to refer to a previous match in the same Regular Expression. The following example illustrates this.
$text=<A>Heres an anchor. </A>; if ($text =~ /<IMG|A)>[\w\s\.]+<\/\1>/i) {

Print Found an image or anchor tag.


} Output: Found an image or anchor tag.

Explanation of code: This code checks if the scalar $text starts with the tag <IMG> or <A> and ends with corresponding tags <\IMG> or <\A>.

16

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Backreferences (continued)


We can refer to a match in parentheses outside the pattern by a number prefaced with $ (for example, $1m $2, $3, and so on).

In the following example, we convert words to abbreviations using the $1 form of Backreferences:

$name = Anonymous Perl Programmers; $name =~ s/(\w)\w*/$1\./g; Print The meeting of the $name foundation is now in session.; Output: The meeting of the A.P.P. foundation is now in session.

17

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Regular Expressions extensions


In the following example code snippet, we can use (?#...) to add comments to Regular Expressions like this, where we are labeling the matches in an expression:
$text = I see you $text =~ s/^(?# 1st)(\w+) *(?# 2nd)(\w+) *(?# 3rd)(\w+)/$3 $2 $1/; print $text; Output: you see I

Explanation of code: (?#...) are treated as comments; (\w+) are Backreferences, which are remembered as $1, $2, and so on.

18

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Regular Expressions extensions


The lookahead assertions (?=) & (?!...) and lookbehind assertions (?<=EXPR) & (?<!EXPR) work with matches that could happen next, although the match is not actually made. Suppose, for example, that we are looking for Mumbai, Chennai, and Delhi, but we dont know what order theyre in;
$_ = Im going to Mumbai, Chennai and Delhi.; Print Found all three. if /(?=.*Chennai)(?=.*Delhi)(?=.*Mumbai)/; Output: Found all three.

Explanation of code: The conditions are noted and then checked if they exist in the pattern, but the order is not checked.

19

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Regular Expressions extensions


In using memory-free parenthesis, to specify some expressions in parenthesis without them being remembered, we can use memory parentheses (?:), as follows:

while (<>) { if (/^(?:exit|quit|stop)$/) { if ($1) { print You typed: $1\n; } else { print Nothing stored.\n;} } } Output: exit Nothing stored

20

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Using modifiers


In using modifiers with m, m//, and s///, the following are the modifiers supported in Perl which could be used with s///.

e It indicates that the right-hand side of s/// is the code to evaluate g It works globally to perform all possible operations i It ignores alphabetic case m It lets ^ and $ match embedded \n characters o It compiles the pattern only once s It lets the . character match newline x It ignores white space in pattern and allows comments

21

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Using modifiers (continued)


In the following example code snippet, we use m//g in list context, wherein it returns a list of all the matches, where we search for four-letter words:
@a=(This is a test =~ m/\w{4}\b/g); Print @a; Output: This test

The following code snippet allows the user to end a program by typing Stop, stop, STOP, StOp, and so on, in a case-insensitive way:
While(<>) { if (m/^stop$/i) { exit; } } Result: When user types stop, the program terminates.

22

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Using modifiers (continued)


By using modifier d with tr///, we can delete not replaced characters from the string.
while (<>) { tr/\r//d; print; } Result: All occurrences of \r\n would become \n.

Explanation of code: Suppose we are reading lines from DOS file, wherein, every line ends with \r\n; the Regular Expression tr/// in the above code deletes unreplaced character \r from every line. This will make all occurrences of \r\n into \n.

23

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Translating strings


Besides the m// and s/// operators, we can also manipulate strings with the tr/// operator, which is the same as y/// operator:
tr/<expr1>/<expr2>/
y/<expr1>/<expr2>/ $_=A quick brown fox jumped over the lazy dog; tr/a-z/A-Z/; print; Output: A QUICK BROWN FOX JUMPED OVER THE LAZY DOG Explanation of Code: The first expression for tr is lower-case alphabets, and second expression is upper case alphabets, tr translates all lower-case alphabets in the scalar to corresponding upper case alphabets. m//, s///, and tr/// works on $_ by default.

24

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Creating Regular Expressions: Translating strings (continued)


In translating strings with tr///, the return value of tr is the number of characters which are translated. This is illustrated through the following code:
$text = x for both x-mas and x-ray; $xcount = ($text =~ tr/x/x/); Print $xcount; Output: 3

Explanation of Code:

In addition to changing the string as per specification, tr returns the number of characters translated in the scalar. In the above code, the number of occurrences of the letter x is 3, and hence, returns 3.

25

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Questions and answers

26

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module summary
Having completed this module, you should be able to: Define Regular Expression Discuss how to use the different parts of Regular Expression such as:
Character classes Alternative match patterns Quantifiers Assertions Backreferences Regular Expression extensions

27

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module 2: References

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module objectives
At the completion of this module, you should be able to: Use Hard references with references to
A scalar Array Hash Subroutine

Use Hard references for


The arrow operator Anonymous arrays, hashes, and subroutines Function call (pass by reference)

Use Symbolic references

29

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Hard References: Reference to a scalar


A hard reference is a variable that stores address of another variable.
$number = 5; $numref = \$number; print $numref; Print $$numref;

Explanation of code:

\ is known as address operator. Hence, the address of variable $number is stored In $numref variable. To dereference a reference to a scalar, we need to precede the reference variable with $ symbol.

30

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Hard References: Reference to an array


Following is an example for reference to an array.
@numarray = (10,20,30,40,50); $arrayref=\@numarray; print $arrayref; print @$arrayref;

Explanation of code: To dereference a reference to an array, we need to precede the reference variable with @ symbol.

31

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Hard References: Reference to a hash


Following is an example for reference to a hash.
$\=\n; %itemhash = (Fan=>32,Kettle=>45,Iron_box=>15,TV=>28); $hashref=\%itemhash; print $hashref; print %$hashref;

Explanation of code: To dereference a reference to a hash, we need to precede the reference variable with % symbol.

32

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Hard References: Reference to a subroutine


Following is an example for reference to a subroutine.
$\=\n; sub myadd() { my($a,$b)=@_; return ($a+$b); } $subref=\&myadd; print $subref; print &$subref(15,-32); Output: CODE(0x95fe654) -17

Explanation of code: To dereference a reference to a subroutine, we need to precede the reference variable with & symbol.

33

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Hard References: Arrow operator


Besides the prefix dereferencers, another popular dereferencing operator is the arrow operator. This operator is specially designed to work with references, much like the prefix dereferencers that you use to dereference the Perl built-in data types.
@array=(Rhino, Elephant, Boar, Hippo, Cat); $arrayref=\@array; Print @$arrayref[0]; Print $arrayref->[0]; Output: Rhino Rhino

Explanation of code:

We can use this arrow operator with an array reference to specify an index into the array.
34 PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Hard References: Anonymous arrays, hashes, and subroutines


One powerful aspect of Perl references is that we can create arrays, hashes, and subroutines by using references, not names, for those constructs. The following code example shows how to create an anonymous array.
$\=\n; $arrayref=[Kalam, Kepler, Einstein, Bose]; print $$arrayref[0]; Output: Kalam

Explanation of code: Every item in the array is a scalar; hence, to dereference an element of the array, we can do so by preceding the reference name with a $ symbol and use the index.

35

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

References: Function call - pass by reference


We may pass reference to a scalar or array or hash through function call. The following example illustrates passing references to two arrays.
Explanation of code: @a=(10,20,30); @b=(15,25,35); sub addem { my ($ref1, $ref2)=@_; for ($i=0; $i<=$#ref1;$i++) { $c[$i]=$$ref1[$i]+$$ref1[$i]; } return @c; } @array=addem(\@a,\@b); print join (, ,@array); In the code example, if we pass the two arrays as is, then, inside the subroutine, these two arrays are stored in a flat list, @_. To identify items in both the arrays distinctly, we can pass references to arrays; the references to these two arrays, namely @a and @b, are passed and stored in the array of the subroutine, @_, and through these two references, the two arrays can be distinctly referenced.

36

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Symbolic Reference
A symbolic reference does not hold the address and type of a data item, but instead holds the name of that item.
$\=\n; $num=5; $numsref=num; print $$numsref;

Explanation of code: Dereferencing the name of the variable makes that name into a reference for data in the variable, a symbolic reference.

37

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Symbolic Reference: Reference to an array


Here is a code example.
$\=\n; @numarray=(5,15,25,18,12,20); $aref=numarray; print @$aref;

Explanation of code: The scalar $aref contains numarray as its value; wherein @numarray is the name of an array; @$aref refers to @numarray. Hence, @$aref refers to the array @numarray.

38

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Questions and answers

39

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Test your understanding


1. What's the difference between these two lines of code?
printf "$i : $$pointer[$i++]; "; printf " and $i : $pointer->[$i++]; \n";

2. What do the following lines of code print out?


$HelpHelpHelp = \\\"Help"; print $$$$HelpHelpHelp;

3. Given that $pointer is a reference to a hash, what's wrong with the following line of code?
$x= ${$pointer->{$i}};

40

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Test your understanding (continued)


4. Why is $b not being set in the following line of code? What do you have to do to make it okay? sub mysub { my ($a, $b) = @_; } 5. What's the best way to pass more than one array into a subroutine?

41

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Test your understanding (continued)


6. Modify the following script to print the value of $this and $that. Are they the same? If not, why not?
#!/usr/bin/perl sub print_coor{ my ($x,$y,$z) = @_; print "$x $y $z \n"; return $x;}; $k = 1; $j = 2; $m = 4; $this = print_coor($k,$j,$m); $that = print_coor(4,5,6);

42

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module summary
Having completed this module, you should be able to: Use Hard references with references to
A scalar Array Hash Subroutine

Use Hard references for


The arrow operator Anonymous arrays, hashes, and subroutines Function call (pass by reference)

Use Symbolic references

43

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module 3: Modules and Packages

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module objectives
At the completion of this module, you should be able to: Create and use packages Create and use modules

45

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Packages
Perl lets provides us with privacy by letting us cut up a program into independent units so that we do not have to worry about interference with the rest of the program. To recognize Perl application in terms of independent units, we use Perl packages, which create namespaces in Perl. A namespace is a space that provides its own global scope for identifiers; it functions as a private programming space.

46

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Packages
We can define a package using the package keyword, succeeded by package name, as follows:
package mypkg;

In the above statement, mypkg is the name of user-defined package. The package definition remains either until another package definition occurs or until the block in which the package was defined terminates.

47

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Packages
The following is an example of a package we store in a file called pkg1.pl:
package pkg1.pl; BEGIN { } sub subroutine1 { print Hello\n; } return 1; END { }

Explanation of code: We use the package statement to switch into the new package, pkg1. Note the BEGIN and END subroutines in the preceding example; the BEGIN subroutine, which can hold initialization code, is called first in a package, and the END subroutine, which can hold cleanup code, is called last. BEGIN and END subroutines are implicitly called by Perl. This code returns a value of true (the statement return 1 to indicate to Perl that the package code loaded okay and is ready to run).

48

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Packages (continued)
To make use of the code in the package pkg1 described in the earlier slide, we can use the require statement as follows in our application:
Require pkg1.pl;

Now, we can refer to the identifiers in pkg1 by qualifying them with the package name followed by the package delimiter, ::, as shown here:
require pkg1.pl; pkg1::subroutine1(); Output: Hello!

49

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Modules
Modules are packages stored in a single file using the same name of the package with the extension .pm.

The code in a module can export its symbols to the symbol table of the code in which we use the module, so we do not have to qualify those symbols with the module name.

50

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Modules (continued)

package Module1; # Perl convention, module names start with cap letters BEGIN { use Exporter(); @ISA = qw(Exporter); @EXPORT = qw(&subroutine1); } sub subroutine1 { print Hello\n; } return 1; END { }

Explanation of code:
When we put a require statement in our code to load a package, that package is loaded at runtime; however, when we put a use statement in our code, that package is loaded during compile time itself. The name of the file should be the same as the module name followed by a .pm extension. This Module uses the Perl Exporter module to export a Subroutine, subroutine1.
51 PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Modules (continued)
We can determine name of the current package by using the built-in identifier __PACKAGE__.

For example, we can print the current package name from a subroutine, subroutine1, in pkg1, like this:
package pkg1; sub subroutine1 { print __PACKAGE__; } return 1;

When we call subroutine1 from any Perl script, the subroutine displays the name of the package in which it is defined.
Explanation of code: require pkg1.pl; pkg1::subroutine1(); Output: pkg1 The subroutine subroutine1 belongs to the scope of the package pkg1. Hence, value of __PACKAGE__ is pkg1 inside the package pkg1
Copyright IBM Corporation 2010

52

PERL Scripting

Learning and Knowledge Education India IBM India Pvt. Ltd.

Modules (continued)
We use the package statement to declare the same package in two or more files. The following example codes illustrates this:
package pkg1; # filename: file1.pl sub hello { print Hello!\n; } return 1; package pkg1; # filename: file2.pl sub hello2 { print Hello again!\n; } return 1;

Now, we can require both file1.pl and file2.pl in code and use hello and hello2 from the same package, pkg1, which is defined in the two files.
require file1.pl; require file2.pl; pkg1::hello(); pkg2::hello2();

Output : Hello! Hello again!

53

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Modules (continued)
If we do not want the symbols from a module to be automatically exported, but rather exported on request, then, we can use the built-in variable EXPORT_OK, as illustrated in the following code:
# Filename: Module1.pm package Module1; BEGIN { use Exporter(); @ISA = qw(Exporter); @EXPORT_OK = qw(&subroutine1); } sub subroutine1 { print Hello!\n; } return 1;

# Filename: main1.pl use Module1 qw(&subroutine1); subroutine1(); Output: Hello!

Code in file main1.pl, that uses this module Module1 can import the subroutine, subroutine1, but that subroutine is not exported by default. The code shows how subroutine1 is imported.
54 PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Modules (continued)
We can override any built-in subroutine, by defining a subroutine with the same name as built-in subroutine in our module.

The following example illustrates this phenomenon:


# Filename: Module1.pm package Module1; BEGIN { use Exporter; @ISA = qw(Exporter); @EXPORT = qw(&exit); } sub exit { print Why do you want to quit?\n; } return 1;

55

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Modules (continued)
The following code example illustrates a Perl script using the module Module1, and exit subroutine is called.
# Filename: myMain1.pl use Module1; exit; print Im still here!\n; Output: Why do you want to quit? Im still here!

Explanation of code: When we call exit subroutine, the default exit subroutine is not called; but, rather the exit subroutine defined in the module Module1 is called. This is because the exit subroutine defined in Module1 overrides the default exit subroutine. If we want to call the default exit subroutine, then, we can invoke it as: CORE::exit; this is because, the CORE pseudo package always holds the original built-in functions.
56 PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Modules (continued)
Now, let us define the package Module1, the file named as Module1.pm.
package Module1; # Filename: Module1.pm BEGIN { use Exporter(); @ISA = qw(Exporter); @EXPORT = qw(&subroutine1 $variable1); } sub subroutine1 { print Hello!\n; } $variable1 = 100; return 1;

57

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Modules (continued)
When we run the script loadsub.pl, Perl calls AUTOLOAD in the Autoload.pm module to look for subroutine1. The code in the AUTOLOAD subroutine first confirms that Perl is looking for subroutine1 and then loads in that subroutines module, Module1. Finally, it calls subroutine1, which prints the message. The following is the output:
Output : Hello!

58

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Questions and answers

59

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Test your understanding


1. What is the difference between including a module using require statement and use statement?

2.
3. 4.

Why do we need to return a value 1 with the return statement at the end of a package definition in Perl?
Can we override built-in subroutines in Perl? Can we define more than one package in a file?

5.
6. 7.

Can we define a single package in more than one file?


What is the difference between @EXPORT and @EXPORT_OK? In the statement pkg1::subroutine1; what is the significance of the symbol ::

60

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module summary
Having completed this module, you should be able to: Create and use packages Create and use modules

61

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module 4: Object Orientation

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module objectives
At the completion of this module, you should be able to: Create a class Create an object Create and use Class methods and Instance methods Use access methods Use constructors

63

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Classes
In Perl, a class is a package that provides methods to other parts of a program. We can consider a class as an objects type. We can use a class to create an object, and then we can call the objects methods from our code. To create an object, we call constructor of a class, which is a method named new. This constructor returns a reference to a new object of the class. Internally, the constructor uses the Perl function bless to forge a connection between a reference to the data of new object and a class, thereby creating an object.

64

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Classes (continued)
In the following example code, Class1 is the name of a class which supports a constructor named new.

In constructor, we create a reference to an anonymous hash that will hold an objects data, bless that hash into the current class, and then return that object reference as the constructors return value:
package Class1; # File name: Class1.pm sub new { my $self = {}; bless ($self); retutrn ($self); } return 1;

65

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects
In Perl, we call an object an instance of a class, and the objects subroutines instance methods, or member functions, or just methods. Besides subroutines, we can also store data items in objects, and such items are called data members or instance data. To create an object, we call a classs constructor, which is usually named new. The following code example shows creation of an object from class developed previously, class1:
use Class1; my $object1 = Class1->new();

Explanation :
The new subroutine returns a reference to the object, which is assigned to a scalar. Using $object1, the members of the class can be accessed. The class Class1 doesnt have any data members or methods (other than new) defined. Unless members are defined, there is no purpose for the object to exist. In the succeeding example, let us see how do we add members to the class.
66 PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Methods
Methods are subroutines built into a class and therefore built into the objects we create from that class. We can classify the use of methods into the following:

The private methods are intended for use inside the class whereas public methods are intended for use outside the class. The private methods are only called inside the object itself by other parts of the object. When we have an object that supports methods, we can use that objects methods like this, where we use the calculate method to work with the two values in $operand1 and $operand2, and store the result of the calculation in $result:
$result = $object1->calculate($operand1, $operand2);

67

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Methods (continued)


Perl has two types of methods: class methods and instance methods. Instance methods, like the calculate example here, are invoked on objects and are passed a reference to an object as their first argument. This means that calculate actually gets three arguments: the reference to the object, followed by the two operands. Class methods are invoked on a class and are passed the name of that class as their first argument. For example, the constructor named new we saw in the previous section is a class method:
my $object1 = Class1->new();

68

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Data members


We can also store data members in objects. Perl hides data behind access methods, which means that instead of retrieving data directly, we might use a method named, say, getdata, to read the data:
my $data = $object1->getdata();

By using access methods this way, we can control access to our objects data so that other parts of the program do not, for example, set that data to a value we consider illegal. We use methods to define our objects interface to the rest of the program.

69

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Inheritance
Using inheritance, we can derive a new class from an old class, and the new class will inherit all the methods and member data of the old class. The new class is called the derived class, and the original class is called the base class. For example, if we have a class named vehicle, we may derive a new class named car from vehicle, and add a new method, horn, which, when called, prints beep. In that way, we have created a new class from a base class and augmented that class with an additional method.

70

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Constructors
Constructors are for more than just creating objects; we also initialize an object in its constructor.

The following example code illustrates the above point:


package Class1; sub new { my $self = {}; # An anonymous hash created, and a reference, $self designated to it shift; # to remove first argument, class name, from the arg list stored in @_,

$self->{DATA_ITEM_1} = shift; # DATA_ITEM_1 and DATA_ITEM_2 are $self->{DATA_ITEM_2} = shift; # keys of anonymous hash bless ($self); # bless function binds the hash reference with object return $self; } return 1;

71

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Constructors (continued)


Now, we can call this constructor from a script, and assign the returned reference to a scalar (object reference).

With this object reference, we can access the data items passed. The following example illustrates this:
use Class1; my $object = Class1->new(1,2); print Data item 1 = , $object->{DATA_ITEM_1}, \n; print Data item 2 = , $object->{DATA_ITEM_2}, \n;

72

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Constructors (continued)

print Class1 supports these methods: , join(, , Class1->get_interfaces()); package Class1; sub new { $class = shift; my $self = {}; bless ($self); return $self; } sub get_interfaces { return new, get_interfaces; } Output: Class1 supports these methods: new, get_interfaces

73

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Instance method


When we invoke a class method, the name of the class is passed to the method as the first argument in the argument list.

When we invoke a method of an object, a reference to that object is passed to the method as the first argument; using this reference, we can reach the objects internal data and methods. The following example code illustrates significance of object method:
1 package Class1; # Filename: Class1.pm 2 sub new { 3 my $class = shift; 4 my $self = {}; 5 bless ($self); 6 return $self; 7 }

8 sub addem { 9 my ($obj, $a, $b) = @_; 10 return $a + $b; 11 }

74

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Instance method (continued)


Now, let us write an application to call this method addem of the class, Class1.

use Class1; $math_obj = Class1->new(); print 2 + 2 = , $math_obj->addem(2,2); Output: 2+2=4

Explanation :

new() method returns reference to object, which is assigned to the scalar $math_obj.
We can invoke the instance method addem with this variable $math_obj which stores reference to the object.

75

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Instance variables


The data we store in an object is called object data, or instance data. The following example code illustrates object data:
package Class1; sub new { my $self = { }; $self->{NAME} = Mohankumar; bless($self); return $self; }

76

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Instance variables (continued)


Now, when we create an object of this class, we can refer to the data in that object like this:
Use Class1; My $object1 = Class1->new(); Print This persons name is , $object1->{NAME}, \n; Output: The persons name is Mohankumar

77

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Create data access methods


We can use data access methods to restrict access to an objects instance data. We usually create a pair of methods, a get method and a set method, to provide access to data. The following example code illustrates this phenomenon:
sub set_name {
shift; $name = shift; } }

sub get_name {
return $name;

78

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Objects: Create data access methods (continued)


The methods set_name and get_name are defined in the class, Class1. Let us invoke these two methods from our script, to access the data.
use Class1; My $object = Class1->new(); $object->set_name(Karthik); Print The persons name is , $object->get_name(), \n; Output: The persons name is Karthik

79

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Questions and answers

80

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Test your understanding


1. What does the bless() function do? 2. What is wrong with the following code?
{ my $x; my $y; $x = \$y; }

3. Modify the following function to print black if no parameters are passed to it:
sub makeCup { my ($class, $cream, $sugar, $dope) = @_; print "\n================================== \n"; print "Making a cup \n"; print "Add cream \n" if ($cream); print "Add $sugar sugar cubes\n" if ($sugar); print "Making some really nice coffee ;-) \n" if ($dope); print "================================== \n"; }

81

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module summary
Having completed this module, you should be able to: Create a class Create an object Create and use Class methods and Instance methods Use access methods

Use constructors

82

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module 5: Perl Documentation

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module objectives
At the completion of this module, you should be able to: Give an overview on the formatting language for Perl documentation

84

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Plain Old Documentation (POD)


POD is a formatting language for documentation, and it was designed to make it easy to create documentation in many different formats.

We can use POD right in our Perl code, as we would normal documents; when we want to create our documentation, we run a POD translator directly on our Perl source code file. The Perl interpreter will ignore the POD in our Perl programs.
=head1 Simulation of Named Characters =head2 This example uses hashes This example: =over 4 =item 1 Shows how to set up two named parameters = item 2 Shows how to set up default for arguments =cut

85

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Plain Old Documentation (continued)


Let us analyze the code in the previous slide, and understand the meaning of the terms used in the code.

=head1 heading - Specifies a level 1 heading =head2 heading - Specifies a level 2 heading =item text =over # =back =cut - Specifies an item in a list - Specifies indentation - Cancels indentation - Ends the POD

86

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Questions and answers

87

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Test your understanding


Write a Perl script that accepts a pattern and name of a file from the user, and displays the number of occurrences of the pattern in the file. Create a POD for the script, which should contain guidelines about working with the script.

88

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module summary
Having completed this module, you should be able to: Give an overview on the formatting language for Perl documentation

89

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module 6:
Comprehensive Perl Archive Network

(CPAN)

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module objectives
At the completion of this module, you should be able to: Give an overview of the CPAN

91

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Overview
CPAN is Comprehensive Perl Archive Network. It is practically an endless source of Perl modules, packages, utilities, ports, as well as documentation about functions and Perl concepts. To get to CPAN, go to www.cpan.org.

92

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Overview (continued)
How to contribute to CPAN: 1. First, get in contact with the Perl Authors Upload Server (PAUSE), a server dedicated to CPAN authors. You can get details at the PAUSE page at www.cpan.org/modules/04pause.html. 2. You will be instructed to send a message (with your name, e-mail address, description of the module, and so on) to modules@perl.org to get registered as a module author. 3. After you e-mail PAUSE with the requested information, you will get an email in a few weeks, and you can select a password, which you will need to upload your module.

93

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Questions and answers

94

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Test your understanding


1. Visit the site www.cpan.org. Go through the modules, tutorials on various Perl concepts, manual pages of subroutines. Explore the site.

2. Verify the difference between visiting www.perl.org/CPAN/ and www.cpan.org.

95

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Module summary
Having completed this module, you should be able to: Give an overview of CPAN

96

PERL Scripting

Copyright IBM Corporation 2010

Learning and Knowledge Education India IBM India Pvt. Ltd.

Bibliography
Reference Books: PERL Black Book by Steven Holzner, Dreamtech Press. Learning Perl by Randal L Schwatz, Tom Phoenix, and Brian Foy. Web sites: http://work.lauralemay.com/samples/perl.html http://www.ewebprogrammer.com

97

PERL Scripting

Copyright IBM Corporation 2010

Вам также может понравиться