Академический Документы
Профессиональный Документы
Культура Документы
Perl Scripting
Day 2 session
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
PERL Scripting
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
Regular Expressions
Regular Expressions are meta-characters that have special meaning to Perl and that could be used to match patterns in a string.
Quantifiers
Assertions Backreferences Regular Expression extensions
PERL Scripting
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
Characters (continued)
Char
| () []
Meaning
It matches either of the patterns separated by this alternator character Parenthesis denotes grouping; "storing" Brackets denote Character class
{}
\
PERL Scripting
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:
PERL Scripting
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:
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
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
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
}
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
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
\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
14
PERL Scripting
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
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
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
Explanation of code: (?#...) are treated as comments; (\w+) are Backreferences, which are remembered as $1, $2, and so on.
18
PERL Scripting
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
while (<>) { if (/^(?:exit|quit|stop)$/) { if ($1) { print You typed: $1\n; } else { print Nothing stored.\n;} } } Output: exit Nothing stored
20
PERL Scripting
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
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
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
24
PERL Scripting
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
26
PERL Scripting
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
Module 2: References
Module objectives
At the completion of this module, you should be able to: Use Hard references with references to
A scalar Array Hash Subroutine
29
PERL Scripting
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
Explanation of code: To dereference a reference to an array, we need to precede the reference variable with @ symbol.
31
PERL Scripting
Explanation of code: To dereference a reference to a hash, we need to precede the reference variable with % symbol.
32
PERL Scripting
Explanation of code: To dereference a reference to a subroutine, we need to precede the reference variable with & symbol.
33
PERL Scripting
Explanation of code:
We can use this arrow operator with an array reference to specify an index into the array.
34 PERL Scripting
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
36
PERL Scripting
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
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
39
PERL Scripting
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
41
PERL Scripting
42
PERL Scripting
Module summary
Having completed this module, you should be able to: Use Hard references with references to
A scalar Array Hash Subroutine
43
PERL Scripting
Module objectives
At the completion of this module, you should be able to: Create and use packages Create and use modules
45
PERL Scripting
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
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
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
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
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
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
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
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();
53
PERL Scripting
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;
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
Modules (continued)
We can override any built-in subroutine, by defining a subroutine with the same name as built-in subroutine in our module.
55
PERL Scripting
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
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
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
59
PERL Scripting
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.
60
PERL Scripting
Module summary
Having completed this module, you should be able to: Create and use packages Create and use modules
61
PERL Scripting
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
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
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
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
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
68
PERL Scripting
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
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
Objects: Constructors
Constructors are for more than just creating objects; we also initialize an object in its constructor.
$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
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
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
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 }
74
PERL Scripting
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
76
PERL Scripting
77
PERL Scripting
sub get_name {
return $name;
78
PERL Scripting
79
PERL Scripting
80
PERL Scripting
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
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
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
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
=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
87
PERL Scripting
88
PERL Scripting
Module summary
Having completed this module, you should be able to: Give an overview on the formatting language for Perl documentation
89
PERL Scripting
Module 6:
Comprehensive Perl Archive Network
(CPAN)
Module objectives
At the completion of this module, you should be able to: Give an overview of the CPAN
91
PERL Scripting
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
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
94
PERL Scripting
95
PERL Scripting
Module summary
Having completed this module, you should be able to: Give an overview of CPAN
96
PERL Scripting
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