Linux, Perl - LX222VIS
Linux, Perl - LX222VIS
Master Visuals
ERC2.1
Publishing Information
This publication has been produced using BookMaster (Program Number 5668-015),
the Document Composition Facility (Program Number 5748-XX9), and Freelance for
Windows. It was printed on the IBM PostScript Printer.
Trademarks
IBM is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the
United States, or other countries, or both:
AIX
OS/2
BookMaster
IBM
Contents
Course Presentation Material Overview
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ix
Units
Unit 1. Overview . . .
Historical Perspective .
The Usability of Perl .
Availability and Support
Elementary Perl Ideas
Useful Addresses . . .
Summary . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-1
1-2
1-3
1-4
1-5
1-6
1-7
2-1
. 2-2
. 2-3
. 2-4
. 2-5
. 2-6
. 2-7
. 2-8
. 2-9
2-10
2-11
2-12
2-13
2-14
2-15
2-16
2-17
2-18
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
3-1
3-2
3-3
3-4
3-5
3-6
3-7
iii
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-8
3-9
4-1
. 4-2
. 4-3
. 4-4
. 4-5
. 4-6
. 4-7
. 4-8
. 4-9
4-10
4-11
4-12
4-13
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5-1
. 5-2
. 5-3
. 5-4
. 5-5
. 5-6
. 5-7
. 5-8
. 5-9
5-10
5-11
5-12
5-13
5-14
5-15
5-16
5-17
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-1
6-2
6-3
6-4
6-5
6-6
6-7
6-8
6-9
iv
Pattern Multipliers . . . . . . . . . . . . . . . . . .
Multiplier Examples . . . . . . . . . . . . . . . . .
Parentheses as Memory . . . . . . . . . . . . . .
Parentheses as Memory Example . . . . . . .
Anchoring Patterns . . . . . . . . . . . . . . . . .
Pattern Precedence . . . . . . . . . . . . . . . . .
The Match Operator . . . . . . . . . . . . . . . . .
The Pattern Binding Operators . . . . . . . . .
The Substitution Operator . . . . . . . . . . . . .
Match and Substitution Modifiers . . . . . . . .
Substitution Examples . . . . . . . . . . . . . . .
Matching Operator Special Variables 1 . . .
Matching Operator Special Variables 2 . . .
Greedy Matching . . . . . . . . . . . . . . . . . . .
Regular Expression Metacharacter Summary
Summary . . . . . . . . . . . . . . . . . . . . . . . .
Unit 7. String and Array Processing
Objectives . . . . . . . . . . . . . . . . . . . .
Generalized Quotes . . . . . . . . . . . . .
The here Document . . . . . . . . . . . . .
Locating a Substring . . . . . . . . . . . .
Locating a Substring Example . . . . . .
Substring Extraction . . . . . . . . . . . . .
Substring Replacement . . . . . . . . . .
Alphabetic Case Operators . . . . . . . .
The Translation Operator . . . . . . . . .
Translation Examples . . . . . . . . . . . .
The map() Operator . . . . . . . . . . . . .
The grep() Operator . . . . . . . . . . . . .
Breaking a String Apart . . . . . . . . . .
The Quote Words Operator: qw() . . .
Joining a List Together . . . . . . . . . . .
The sort() Operator . . . . . . . . . . . . .
Sorting Examples . . . . . . . . . . . . . .
Summary . . . . . . . . . . . . . . . . . . . .
6-10
6-11
6-12
6-13
6-14
6-15
6-16
6-17
6-18
6-19
6-20
6-21
6-22
6-23
6-24
6-25
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
7-1
. 7-2
. 7-3
. 7-4
. 7-5
. 7-6
. 7-7
. 7-8
. 7-9
7-10
7-11
7-12
7-13
7-14
7-15
7-16
7-17
7-18
7-19
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
8-1
8-2
8-3
8-4
8-5
8-6
8-7
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9-1
. 9-2
. 9-3
. 9-4
. 9-5
. 9-6
. 9-7
. 9-8
. 9-9
9-10
9-11
9-12
9-13
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8-8
8-9
8-10
8-11
8-12
8-13
8-14
8-15
10-1
10-2
. 10-3
. 10-4
. 10-5
. 10-6
. 10-7
. 10-8
. 10-9
10-10
10-11
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11-1
11-2
11-3
11-4
11-5
11-6
11-7
11-8
11-9
vi
Summary
11-10
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12-1
. 12-2
. 12-3
. 12-4
. 12-5
. 12-6
. 12-7
. 12-8
. 12-9
12-10
12-11
12-12
12-13
12-14
12-15
12-16
12-17
12-18
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
13-1
. 13-2
. 13-3
. 13-4
. 13-5
. 13-6
. 13-7
. 13-8
. 13-9
13-10
13-11
13-12
13-13
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
14-1
14-2
14-3
14-4
14-5
14-6
14-7
14-8
14-9
vii
14-10
14-11
14-12
14-13
14-14
14-15
14-16
14-17
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15-1
. 15-2
. 15-3
. 15-4
. 15-5
. 15-6
. 15-7
. 15-8
. 15-9
15-10
15-11
15-12
15-13
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
16-1
16-2
. 16-3
. 16-4
. 16-5
. 16-6
. 16-7
. 16-8
. 16-9
16-10
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
viii
ix
Unit 1. Overview
1-1
Historical Perspective
Developed by Larry Wall when working at JPL
First released in 1987
Initially used for text processing and report generation
Perl is short for
Practical Extraction and Report Language
Designed to be practical (easy to use, efficient, complete) rather than
beautiful (tiny, elegant, minimal)
Perl is freeware
Copyright IBM Corp. 1999, 2001
Released for use under the Artistic and/or GNU Public License
LX222102T
1-2
1-3
1-4
; terminates statements
# comments to end of line
LX222108T
1-5
Useful Addresses
The Perl homepage is http://www.perl.com/
Source code available from http://www.perl.com/CPAN/
Perl news and gossip at: http://use.perl.org/
Perl for Windows from http://www.activestate.com/
Start your Perl programs with #!/usr/bin/perl
Perl may be better stated as:
Pretty Exciting and Rather Logical
LX222110T
Summary
Perl is:
A scripting language
A general purpose programming language
Designed for practicality
Widely used and well supported
Any questions on the overview?
LX222100T
2-1
Objectives
After completing this unit, you should be able to use:
Basic scalar data
Scalar variables
Assignment operators
Arithmetic operators
String operators
Operator precedence and associativity
Variable interpolation
Copyright IBM Corp. 1999, 2001
LX222200T
2-2
Scalar Data
Perl's simplest data type is scalar data
Scalar data can be:
Strings of characters
"hello", "goodbye\n"
'yes',
'no'
Numbers
5, 2.74, 68, 3.25e20, 0777, 0xFF32
Copyright IBM Corp. 1999, 2001
2-3
Scalar Strings
Perl strings:
can be of unlimited length
can contain any 8-bit data
Perl strings come in two types:
Single-quoted strings
'literal text'
'doesn\'t'
#
'perl\\test'
#
Double-quoted strings
"\"Don't go!\" she said." # \ protects "
"low\tbright\tblack\twhite"
# \ introduces escapes
"\nThe value is $val.\n" # variable substitution
LX222206T
2-4
Representation
eq
Not Equal
ne
Less than
lt
Greater than
gt
le
ge
LX222208T
becomes
"helloworld"
'goodbye'."\n"
becomes
"goodbye\n"
"out"." "."var"
becomes
"out var"
"red" x 3
becomes
"redredred"
"bill" x (1+2)
becomes
"billbillbill"
(8-1) x 5
becomes
"77777"
Repetition operator: x
LX222210T
2-6
Scalar Numbers
Decimal numbers
Integer literals
11, 25, -2001, 15428, 333, -1997
Float literals
1.22, -8.642, 6.512e43, -12e-16, 1.7E12
Octal numbers: 040, 016, 0777, 011, 012, 013
Hexadecimal numbers: 0x23, 0XAF
Can contain _ for readability 123_456_789, 0x0000_632b
Copyright IBM Corp. 1999, 2001
LX222212T
2-7
Arithmetic Operators
Operation
Addition
Symbol
+
Example
3 + 2
Result
5
Subtraction
3 - 2
Multiplication
3 * 2
Division
3 / 2
1.5
Exponentiation
**
3 ** 2
Modulus
3 % 2
1
LX222214T
Representation
==
Not equal
!=
Less than
<
Greater than
>
<=
>=
LX222216T
! not
# true
# false
# true (1 < 2)
# true (2 < 3)
# false
! ("A" gt "Z")
not ("A" lt "Z")
# true
# false
LX222218T
2-10
is
is
1 + (2 * 3)
(1 / 2) + 3
# 7
(not 9)
# 3.5 (not 1/5)
is
is
(3 + 1) - 2
# left associative
3 ** (1 ** 2) # right associative
LX222220T
2-11
Scalar Variables
A scalar variable stores a single value
The variable name must start with a letter or underscore and can
contain letters numbers or underscores
Variable names are case-sensitive
A scalar variable is prefixed by a $
The variable name can be surrounded by braces to separate it from
following text
Example:
$A
$a
$a_very_long_name
${var1} $_myvar
LX222224T
2-13
Scalar Assignment
Assignment creates variables if they do not already exist
Assignment statements are evaluated according to precedence
Assignment has low precedence, evaluated after most other
expressions
Assignment is an operator that returns the value assigned
Examples:
Copyright IBM Corp. 1999, 2001
$a =
${b}
$d =
${e}
$x =
17 + 22;
= $c;
"hello";
= 22 x 3;
$y = $z = 0;
LX222226T
2-14
#
#
#
#
Today
Today
Today
Today
is
is
is
is
wrong
Monday
Monday
Monday
LX222228T
2-15
# same as $g = $g + 11;
# same as $e = $e * 3;
# same as $str = $str . "a";
/=
%=
**=
x=
&&=
||=
LX222230T
2-16
#
#
#
#
increment
increment
decrement
decrement
before use
after use
before use
after use
Example:
$x = 11;
print ++$x;
print $x++;
print --$x;
print $x--;
#
#
#
#
prints
prints
prints
prints
12,
12,
12,
12,
$x
$x
$x
$x
is
is
is
is
12
13
12
11
LX222232T
2-17
Summary
Basic scalar data
Scalar variables
Assignment operators
Arithmetic operators
String operators
Operator precedence and associativity
Variable interpolation
LX222202T
3-1
Objectives
After completing this unit, you should be able to:
Send output to STDOUT with print
Get input from STDIN with the input operator
Use the chop and chomp operators to deal with line delimiters
LX222300T
LX222304T
3-3
LX222306T
3-4
#!/usr/bin/perl -w
print 2 * $x;
# output: 0 and the warning message:# Use of uninitialized value at - line 1.
LX222308T
3-5
3-6
3-7
chomp $x;
chomp( $x = <STDIN>);
$count = chomp( $x = <STDIN> );
LX222314T
3-8
Summary
Send output to STDOUT with print
Get input from STDIN with the input operator
Use the chop and chomp operators to deal with line delimiters
LX222302T
4-1
Objectives
After completing this unit, you should be able to use:
Statement blocks
if/else statement
elsif branch
the unless variation
while and until statements
for statement
foreach statement
Copyright IBM Corp. 1999, 2001
LX222400T
4-2
LX222404T
4-3
if ( $month < 13 ) {
print "A possible month of the year" ;
}
else {
print "Invalid month ($month) > 12\n";
}
LX222406T
4-4
if ($name eq 'Tom') {
print "Hello Tom!\n" ;
} elsif ($name eq 'Richard') {
print "G'day Richard\n" ;
} elsif ($name eq 'Harry') {
print "Hi Harry!\n" ;
} elsif ($hour < 12) {
print "Good Morning $name\n" ;
} else {
print "Hello $name\n" ;
}
4-5
LX222408T
do {
print $x -- ;
sleep 1;
} while ( $x >= 0 );
LX222412T
4-7
# print $_;
# chop $_;
# chomp $_;
LX222414T
4-9
LX222418T
4-10
LX222420T
4-11
4-12
Summary
Statement blocks
if/else statement
elsif branch
the unless variation
while and until statements
for statement
foreach statement
LX222402T
5-1
Objectives
After completing this unit, you should be able to use:
Lists
Arrays
Array variables
Array operators
LX222500T
Defining a List
A list is a comma-separated, ordered set of scalar values
Often enclosed in parentheses
Syntax:
(itema, itemb, itemc)
Widely used in Perl by
the foreach loop
many functions and list operators
LX222504T
List Examples
Simple Lists:
(1,2,3,4,5,6,7)
('tony', 'toni', 'toney')
(7.623, 'hi', '', "world", -44, undef)
Expressions:
($v, $w*$x, $y+$z)
The Empty List:
()
Copyright IBM Corp. 1999, 2001
List Assignment:
($l, $m, $n) = (1, 2, 3);
($l, $m) = ($m, $l);
LX222508T
5-4
# (1,2,3,4,5,6,7,8,9,10)
# ("A","B","C","D","E")
Example:
foreach (1 .. 1_000) { ... }
print "A" .. "Z", "\n";
LX222506T
Array Assignment
Simple Assignment:
@numbers =
@my_nums =
@one_num =
@more_nums
(1,2,3,4,5);
@numbers;
# a copy of @numbers
(1);
# list with one member
= (5,@numbers); # list with six members
Special Cases:
$count = @numbers;
# number of elements: 5
$count = scalar(@numbers); # the same explicitly
$last = $#numbers;
# index of the last element: 4
LX222512T
@nums = (2,4,6);
$p = $nums[0];
$nums[0] = 5;
$q = $nums[$p];
$r = $nums[$p-1];
$nums[2] += 5;
$nums[4] += 1;
$nums[-1] += 5;
#
#
#
#
#
#
#
2
(5,4,6)
6
4
(5,4,11)
(5,4,11,undef,1)
(5,4,11,undef,6)
LX222514T
5-8
# (9, 8, 7, 6)
# (5, 2, 7, 2, 9)
# (5, 2, 4, 2, 3)
LX222516T
5-9
@old = (5,21,38,16) ;
push(@old,99,77) ;
#
$new = 88 ;
push(@old,$new) ;
#
$last = pop(@old) ;
#
$last = pop(@old) ;
#
(5,21,38,16,99,77)
(5,21,38,16,99,77,88)
88
(5,21,38,16,99,77)
77
(5,21,38,16,99)
LX222518T
5-10
@old = (5,21,38,16) ;
$new = 66 ;
unshift(@old, $new) ;
#
shift(@old) ;
#
$next = shift(@old) ;
#
while ( $next = shift(@old)
(66,5,21,38,16)
(5,21,38,16)
5 (21,38,16)
) { ... }
LX222520T
5-11
@ra = (6,5,4,3,2,1) ;
splice(@ra, 3, 1, ('dog','cat')) ;
# (6,5,4,'dog','cat',2,1)
splice(@ra, 3, 0, ('horse')) ;
# (6,5,4,'horse','dog','cat',2,1)
splice(@ra, 3) ;
# (6,5,4)
LX222522T
5-12
(40,30,20,10)
LX222524T
@rainbow = ('red','orange','yellow','green','blue',
'indigo','violet');
@alphabet = sort(@rainbow);
# blue,green,indigo,orange,red,violet,yellow
@nums = (1,2,3,4,5,10,20,30,40,50);
sort @nums;
# (1,10,2,20,3,30,4,40,5,50) :-(
LX222526T
5-14
@output = ("hello\n","world\n");
$count = chomp (@output); # @output is ("hello","world")
@output = ("hello\n","world\n");
chop (@output); # @output is ("hello","world")
LX222528T
5-15
@pat = (1,"z",2,"y",3,"x");
$p = 3;
print "This output is $pat[1]" ;
print "This output is $pat[$p-1]" ;
print "This output is @pat" ;
print "This output is ", @pat;
print "This output is @pat[2,3]" ;
print "This output is @pat[$p*2-1]" ;
#
#
#
#
#
#
z
2
1 z 2 y 3 x
1z2y3x
2 y
x
5-16
Summary
Lists
Arrays
Array variables
Array operators
LX222502T
6-1
Objectives
After completing this unit, you should understand the concepts of
regular expressions and be able to use:
Single-character patterns
Grouping patterns
Anchoring patterns
Pattern precedence
The matching and substitution operators
LX222600T
6-3
Types of Patterns
Single character patterns
a single alphanumeric character matches itself
a single dot . matches any single character except a newline
a list of characters in [ ] matches any single character contained
this is called a character class
There are also:
Multiple character patterns
Anchoring patterns
Copyright IBM Corp. 1999, 2001
6-4
/[2468]/
/[0-5]/
/[789-]/
/[a-z]/
lowercase alphabetic
/[0-9]/
/[a-z]/
/[A-Za-z0-9_]/
LX222608T
6-5
digits: [0-9]
non-digits: [0-9]
word characters: [A-Za-z0-9_]
non-word characters: [A-Za-z0-9_]
whitespace: [ \t\n\r\f]
non-whitespace: [ \t\n\r\f]
Example:
if ( /\d/ ) { print "Found a digit!"; }
LX222610T
6-6
6-7
A Sequence of Patterns
A sequence of patterns, matches the sequence of characters
matched by the patterns
Example:
if ( /112/ ) { print "Emergency number!"; }
Match 1 followed by 1 followed by 2
if ( /XyzzY/ ) { print "Knows the magic word!"; }
Match X then y then z then z then Y
if ( / 2\.4\.\d/ ) { print "Reasonably current"; }
Copyright IBM Corp. 1999, 2001
Match 2.4.any-single-digit
LX222614T
6-8
Matching Alternatives
Alternation enables multiple patterns to be tested
Separate the alternatives with a |
Syntax:
pattern1|pattern2
Example:
if ( /you|ewe|yew/ ) { print "Sounds like U"; }
Copyright IBM Corp. 1999, 2001
LX222616T
6-9
Pattern Multipliers
A multiplier is a special character applied to the immediately
preceding pattern
A pattern and its multiplier can match variable numbers of
characters
Syntax:
?
*
+
{m,n}
{m,}
{,n}
{i}
zero or one
zero or more
one or more
from m to n occurrences
m or more
at most n
exactly i occurrences
LX222618T
6-10
Multiplier Examples
/ca?t/
/ye*s/
/wh+y/
/wh{5}o/
/ca{3,}r/
/co{1,4}w/
/A*/
#
#
#
#
#
#
#
ct
cat
ys yes yees yeees . . .
why whhy whhhy whhhhy . . .
whhhhho
caaar caaaar caaaaar . . .
cow coow cooow coooow
yes why who car cow A AA AAA . . .
LX222620T
Parentheses as Memory
Parentheses store the matched text in special registers for reuse
later in the pattern
One register for each pair of parentheses:
\1 represents the text matched within the first parentheses
\2 represents the text matched within the second ...
Example:
Copyright IBM Corp. 1999, 2001
/(.)(.).\2\1/
/(\w+)\s+\1/
LX222622T
6-12
DxEkyFkyGxH
match
\1 is x,
\2 is ky
D6Ek9Fk9G6H
match
\1 is 6,
\2 is k9
DxEkyFkyG1H
no
DxEkyFkGxH
no
DxEkyFwG8H
no
LX222624T
6-13
Anchoring Patterns
Anchor patterns match positions not characters in the searched
string
Syntax:
/pattern/
/pattern$/
Example:
/\bpattern/
/\bpattern\b/
/\Bpattern/
/Jim\B/
match
match
match
match
pattern at a boundary
the word pattern
pattern when not a boundary
Jimmy and Jims but not "Jim James"
LX222626T
6-14
Pattern Precedence
Patterns have precedence just like operators
The table lists patterns in descending order of precedence
Name
Parentheses
Multipliers
Sequence/Anchoring
Alternation
Symbols
()
? * + {m,n}
ABC $ \b \B
|
Example:
Copyright IBM Corp. 1999, 2001
xy*z
(xyz)*
t|v$
(t|v)$
matches
matches
matches
matches
6-15
m/From: / ;
/From: / ;
m#/.*/(.*)# ;
m{From: (.*)} ;
LX222630T
6-16
$name = /(\w+)\s+((\w\.?)\s+)?(\w+)/;
while ( $answer ! /[YyNn]/ ) {
print "Enter 'Y'es or 'N'o: ";
chomp($answer = <STDIN>);
}
LX222632T
6-17
s/UNIX/Linux/;
$line = s/Java/Perl/;
s@/usr/local/bin/perl@/usr/bin/perl@;
s{/usr/bin/javac}[/usr/bin/perl -wc];
Only does one replacement
LX222634T
6-18
# /[Yy]/
Global search/replace
$line = s/Java/Perl/g;
Compile the pattern only once
$pattern = shift || die "No pattern supplied!\n";
while ( <> ) { if ( /$pattern/o ) { print; } }
Copyright IBM Corp. 1999, 2001
6-19
Substitution Examples
$_ = "a long, long, long time ago";
s/long/short/;
s/long/MEDIUM/g;
$&
$'
Example:
$_ = "this is a simple sentence" ;
/si.*le/ ;
Copyright IBM Corp. 1999, 2001
print $;
print $&;
print $';
# "this is a "
# "simple"
# " sentence"
LX222640T
6-21
6-22
Greedy Matching
Regular expressions match the longest possible string from a given
start position
Example:
$_ = "this is a simple sentence" ;
/(t.*s)/ ; # $1 is 'this is a simple s'
Multipliers can be made un-greedy by appending ?
/(t.*?s)/ ; # $1 is 'this'
m#<b>(.*?)</b>#sig ; # only bold phrases
LX222644T
6-23
\
{ }
()
Summary
Concepts of Regular Expressions
Single-character patterns
Grouping patterns
Anchoring patterns
Pattern precedence
The matching and substitution operators
LX222602T
7-1
Objectives
After completing this unit, you should be able to:
Use additional quoting functions and the here-doc string
Perform string manipulations:
Locate, select and extract substrings
Map or transliterate characters
Case conversion
Perform more list manipulations:
7-2
Generalized Quotes
Operators that provide alternative string delimiters
Syntax:
q/single quoted string/
qq{double quoted string}
Example:
$string
$string
$string
$string
$string
$string
=
=
=
=
=
=
7-3
7-4
Locating a Substring
index() and rindex() search a string for a sub-string
Both return the location if found or -1 if not found
The location is the position of the start of the sub-string
where characters are numbered from 0
index() searches left-to-right, rindex() right-to-left
Syntax:
index( target, substring, skip)
rindex( target, substring, skip)
Copyright IBM Corp. 1999, 2001
Example:
if ( ($pos = index($t, '../') >= 0) { ... }
LX222708T
7-5
# 1
# 8
# -1
LX222710T
7-6
Substring Extraction
Return a sub-string selected by start-position and length
Syntax:
substr(string, start, length)
Example:
$ls_l = '-rw-r--r-- 1 chrisb 95968 Mar 15 11:26 lx222m71.scr';
$mode = substr($ls_l, 0, 10); # -rw-r--r-$from = 'From: [email protected] (ILS)';
$name = substr($from, 6);
# [email protected] (ILS)
Copyright IBM Corp. 1999, 2001
$line = <>;
$delim = substr($line, -1);
# \n (on Linux!)
LX222712T
7-7
Substring Replacement
substr() can also be the target of an assignment!
Syntax:
substr(string, start, length) = "newstring"
Example:
$hi = "Hello World";
substr($hi, 0, 5) = "Goodbye cruel"; # "Goodbye cruel World"
substr($hi, 8) = "to you";
# "Goodbye to you"
substr($hi, 11, 0) = "all of ";
# "Goodbye to all of you"
substr($hi, 7) = "";
# "Goodbye"
Copyright IBM Corp. 1999, 2001
LX222714T
7-8
print lc $code ;
$key = uc $key ;
print ucfirst lc $name ;
print uc ; # use $_
The default source is $_
LX222716T
7-9
7-10
Translation Examples
$_ = 'hello cruel world :-(' ;
tr/aeiou/AEIOU/;
# 'hEllO crUEl wOrld :-('
tr/l-z/Lx/;
# 'hELLO cxUEL xOxLd :-('
tr/A-Za-z/ /cs;
# 'hELLO cxUEL xOxLd '
tr/a-z/ABCDEFGH/d; # 'HELLO CUEL OLD '
tr/ //d;
# 'HELLOCUELOLD'
$_ = 'Hello World!';
tr/A-Za-z/N-ZA-Mn-za-m/;
tr/A-Za-z/N-ZA-Mn-za-m/;
# Uryyb Jbeyq!
# Hello World!
LX222720T
7-12
7-13
$_ = "root
391
1 0 Mar14 ?
($user, $pid, undef) = split;
($user, $pid, undef) = split /\s+/, $_, 3;
00:00:00 lpd";
LX222726T
7-14
7-15
# needs a trailing \n
# append a dummy (null) value
$domain = 'training.uk.ibm.com' ;
print join '.', reverse split /\./, $domain ;
LX222730T
7-16
<=>
cmp
alphanumeric comparison
LX222732T
7-17
Sorting Examples
@names = qw( one two three four five six );
@sorted = sort (@names);
# five four one six three two
@sorted = sort { $a cmp $b } (@names);
@reversed = sort { $b cmp $a } @names;
# two three six one four five
@numbers = (3,11,5,23,13,7,19,29,17,1) ;
sub lotohi { $a <=> $b }
sub hitolo { $b <=> $a }
@l2h = sort lotohi @numbers;
#1,3,5,7,11,13,17,19,23,29
@h2l = sort hitolo @numbers;
# 29,23,19,17,13,11,7,5,3,1
LX222734T
7-18
Summary
Additional quoting functions and the here-doc string
Perform string manipulations:
Locate, select and extract substrings
Map or transliterate characters
Case conversion
Perform more list manipulations:
LX222702T
7-19
8-1
Objectives
After completing this unit, you should be able to use:
Multidimensional arrays
Associative arrays or hashes
Hash operators
LX222800T
['Fred',
['Wilma',
['Betty',
['Barney',
'M',
'F',
'F',
'M',
'B',
'A',
'M',
'P',
'systems analyst'] ,
'programmer'] ,
'network analyst'] ,
'systems engineer'] )
LX222804T
8-3
Two-Dimensional Arrays
Assignment:
@students = (
['Fred',
['Wilma',
['Betty',
['Barney',
) ;
'M',
'F',
'F',
'M',
'B',
'A',
'M',
'P',
'systems analyst'] ,
'programmer'] ,
'network analyst'] ,
'systems engineer']
8-4
# Barney
LX222808T
8-5
'M',
'F',
'F',
'M',
['B','C','A'],
['A','F','D'],
['M','G','A'],
['P','E'],
'systems analyst'] ,
'programmer'] ,
'network analyst'] ,
'systems engineer']
Element access:
Copyright IBM Corp. 1999, 2001
8-6
key
Fred
Wilma
Betty
Barney
value
systems analyst
programmer
network analyst
systems engineer
LX222812T
8-7
(
=>
=>
=>
=>
'systems analyst' ,
'programmer' ,
'network analyst' ,
'systems engineer'
8-8
8-9
Hash Operators
keys() returns a list of all the keys in a hash
Syntax:
keys(%hash)
Every call to each() returns the next key/value pair from a hash
Syntax:
each(%hash)
Copyright IBM Corp. 1999, 2001
LX222818T
8-10
8-11
8-12
(
=>
=>
=>
=>
['M',
['F',
['F',
['M',
'B',
'A',
'P',
'P',
'systems analyst'] ,
'operator'] ,
'network analyst'] ,
'systems engineer']
LX222824T
# systems engineer
8-14
Summary
Multidimensional arrays
Associative arrays or hashes
Hash operators
LX222802T
9-1
Objectives
After completing this unit, you should be able to:
Define subroutines
Use user-defined subroutines
Return from subroutines
Pass variables to subroutines
Use packages
LX222900T
User-Defined Subroutines
A subroutine or function is a named statement block
The name must be unique within the program
The name must start with an alphabetic or underscore
Syntax:
sub subname {statements}
Example:
sub print_line {
print '-' x 80, "\n";
}
LX222904T
9-3
Calling a Subroutine
Syntax:
&subname
subname()
subname
Example:
&print_line;
print_line();
print_line;
sub myadd {
$debug && print "\$a=$a, \$b=$b\n";
return $a + $b;
}
$a = 1;
$b = 4;
print 3 * myadd(); # 15
$c = myadd();
LX222908T
9-5
sub mypow {
$a; }
$a ** $b; }
LX222910T
9-6
my($value, $exp) ;
my($value, $exp) = (8, 2) ;
my ($title, @ps) = <PS>; # read entire input
local($line) ;
local($line) = <> ; # read entire input, assign first line
local($line) = scalar <> ; # read and assign one line
local $line = <> ; # read and assign one line
LX222912T
9-7
# undef, undef
# undef, undef
sub mysub1 {
print $m, $l; # undef, undef
my $m = 'my-mysub1';
local $l = 'local-mysub1';
mysub2();
print $m, $l; # 'my-mysub1', 'local-mysub1'
}
Copyright IBM Corp. 1999, 2001
sub mysub2 {
print $m, $l;
}
# undef, 'local-mysub1'
LX222914T
9-8
sub mymax {
my $max = shift; # defaults to @_ in subroutines
foreach ( @_ ) {
$_ > $max && $max = $_ ;
}
$max; # return value
}
LX222916T
9-9
A Subroutine Example
#!/usr/bin/perl -w
my ($min, $max, $ave) = minmaxave( 2, 22, -3, 14, 6, 10);
# -3, 22, 8.5
sub minmaxave {
my($min, $max, $sum, $cnt) = (0,0,0,0);
foreach ( @_ ) {
if ($_ < $min) { $min = $_ }
if ($_ > $max) { $max = $_ }
$sum += $_;
++ $cnt;
}
$min, $max, $sum / $cnt;
}
LX222918T
9-10
package utils;
sub min {
$min = shift;
foreach (@_) { if ($_ < $min) { $min = $_ } }
$min;
}
sub max {
$max = shift;
foreach (@_) { if ($_ > $max) { $max = $_ } }
$max;
}
LX222920T
9-11
Summary
Define subroutines
Use user-defined subroutines
Return from subroutines
Pass variables to subroutines
Use packages
LX222902T
10-1
Objectives
After completing this unit, you should be able to:
Use more print operations
Open and close filehandles
Read and write user-defined filehandles
Select the default output filehandle
LX222A00T
Example:
$| = 1;
foreach ( reverse 0 .. 10 ) { print "$_ "; sleep 1; }
{ local $, = "\n"; local $\ = "\n";
print @names; # one field/line and trailing newline
}
LX222A04T
10-3
Filehandles
A filehandle is how Perl refers to open files
We have already seen STDIN, STDOUT and STDERR
Filehandles have no special prefix character
By convention filehandles are in UPPERCASE
LX222A06T
open(INFILE, $filename) ;
open PASSWD, "<$passwd" ;
unless ( open OUTFILE, ">$outfile" ) { ... }
if ( open(LOGFILE, ">> $logfile") { ... }
close(LOGFILE);
close PASSWD;
LX222A08T
10-5
10-6
10-7
10-8
close(REPORT);
close(INVENTORY);
LX222A16T
10-9
10-10
Summary
Use more print operations
Open and close filehandles
Read and write user-defined filehandles
Select the default output filehandle
LX222A02T
11-1
Objectives
After completing this unit, you should be able to use:
More flow control structures
The loop modifiers: last, next and redo
Block labels
LX222B00T
Statement Modifiers
Provide shortcut flow control structures
A simple statement can be followed by a single modifier
Syntax:
statement
control_keyword
test_condition
11-3
expr2
expr3
Example:
Copyright IBM Corp. 1999, 2001
11-4
# skip comments
# skip empty lines
LX222B08T
11-5
11-6
11-7
11-8
{
/who/
and
/what/ and
/when/ and
$opt = 99;
$opt = 1
$opt = 2
$opt = 3
and
and
and
last MENU;
last MENU;
last MENU;
}
LX222B16T
11-9
Summary
More flow control structures
The loop modifiers: last, next and redo
Block labels
LX222B02T
12-1
Objectives
After completing this unit, you should be able to:
Check file types, permissions and other data
Use directories and directory handles
Create and delete directories
Rename and delete files
Create and remove links
Modify permissions, ownership and timestamps
Use filename globbing
Copyright IBM Corp. 1999, 2001
LX222C00T
12-2
-l MYFILE
&&
# filename in $_
LX222C04T
12-3
Test
-r
-w
-x
-o
-e
-f
-d
-l
-z
-s
Condition
file/directory readable
file/directory writable
file/directory executable
file/directory owned by user
file/directory exists
file exists and is a file
directory exists
file exists and is a symbolic link
file exists and has zero size
file exists and has non-zero size
LX222C06T
12-4
12-5
LX222C10T
12-6
Changing Directory
Change current directory of the program
Syntax:
chdir (directory_expression)
Example:
chdir ( "/etc" ) ;
chdir $directory or die "can't chdir to $directory: $!\n";
chdir;
# $HOME
Copyright IBM Corp. 1999, 2001
LX222C14T
12-8
Directory Handles
A Directory Handle can be used to get the names of all the files in a
directory
Directory Handles are always opened read-only: they can only be
used to read filenames
A Directory Handle must be opened before use and should be closed
afterwards to conserve resources
Syntax:
opendir(DIR_HANDLE, directory_name)
closedir(DIR_HANDLE)
Copyright IBM Corp. 1999, 2001
Example:
$dir = "/etc" ;
opendir(DIR,$dir) || die "can't opendir $dir: $!\n";
closedir DIR;
LX222C16T
12-9
12-10
link($today, 'current');
symlink($path, '/tmp/test') or
warn "can't symlink $path: $!\n";
print "$path -> ", readlink($path), "\n"
if -l $path ;
LX222C22T
12-12
# no error checking!
foreach ( @old ) {
unlink || warn "can't unlink $_: $!\n";
}
Copyright IBM Corp. 1999, 2001
LX222C24T
12-13
# 2 hours ago
$now = time;
foreach $file (@files) {
utime($now, $now, $file) or
warn "can't set time on $file: $!\n";
}
LX222C26T
12-14
LX222C28T
12-15
@all_files = <*> ;
@all_progs = glob "/bin/* /usr/local/bin/*" ;
@my_files = <$ENV{'HOME'}/*> ;
while ($filename = glob "/etc/a*") {
print "File name is $filename\n";
}
chmod 0500, <$ENV{'HOME'}/bin/*> ;
unlink </tmp/* /var/tmp/*> ;
LX222C32T
12-17
Summary
Check file types, permissions and other data
Use directories and directory handles
Create and delete directories
Rename and delete files
Create and remove links
Modify permissions, ownership and timestamps
Use filename globbing
LX222C02T
13-1
Objectives
After completing this unit, you should be able to:
Use different ways of running Perl programs
Access command-line arguments
Use Perl's command-line switches
Start Perl's built-in debugger
Read and create embedded documentation
LX222D00T
Running Perl
Perl scripts can always be run by running Perl with the script as an
argument
C:\>perl myscript.pl
On UNIX-like systems the system can run Perl automatically if:
the script has execute permission
the first line is a comment giving the path to the Perl executable
#!/usr/bin/perl
On Win32 systems a batch file (.BAT) can be created with pl2bat
Copyright IBM Corp. 1999, 2001
13-3
13-4
LX222D08T
13-5
$ perl -d myprog.pl *
# start with debugger
C:\> perl -wc myprog.pl
# compile only with warnings
$ ls | perl -nle 'print if -T' # list text files
$ perl -e 'rename $_, lc foreach @ARGV' *
$ perl -pi.bak -e 's/\bJava\b/Perl/ig' *.aw
LX222D10T
13-6
-h
-v
-w
-n
-p
-a
-e
-c
-T
-d
-i
-l
13-7
while(<>) {
@F = split(/\s+/);
$F[0]=/nobody$/ && kill 9, $F[1];
}
LX222D14T
$ENV{PATH} = '/bin:/usr/bin:/usr/local/bin';
$ENV{IFS} = " \t\n\f";
delete @ENV{ qw/CDPATH ENV BASH_ENV/ }; #
LX222D16T
13-9
Debugging Perl
Perl has an integrated source debugger
Started with the -d command-line flag
A text-based interactive environment
Enables viewing and searching code and variables, stepping though
code, breakpoints, automatic actions, ...
Example:
$ perl -d myscript
$ perl -de 1
Loading DB routines from perl5db.pl version 1.0402
Emacs support available.
Enter h or h h' for help.
main::(-e:1):
1
DB<1>
LX222D18T
13-10
LX222D20T
13-11
POD Markup
=head1 heading A top-level (Chapter/Section) heading
=head2 heading The next level heading
=over n Start a list of items, specifying the indent
=item text Supply the label for the next paragraph
=back End the list
=pod Start POD processing
=cut
13-12
Summary
Use different ways of running Perl programs
Access command-line arguments
Use Perl's command-line switches
Start Perl's built-in debugger
Read and create embedded documentation
LX222D02T
14-1
Objectives
After completing this unit, you should be able to:
Understand report formats
Define a report format
Execute a report format
Use filehandles in reports
Use format names
Use placeholders
LX222E00T
Report Formats
A report is declared in a program with a format statement
Formats are associated with filehandles and are usually given the
same name
Syntax:
format FORMATNAME =
report_layout
.
LX222E06T
quantity: @##
$quan
LX222E08T
14-5
A Report Example
format PICKLIST =
________________________________________
|
|
| stock#: @######
quantity: @##
|
$stock,
$quan
| @<<<<<<<<<<<<<<<<<<<<<<<<<<<
|
$desc
| row:
@##
col: @#
bin: @#
|
$row, $col,
$bin
| price: @####.##
store#: @###
|
$price,
$store
|______________________________________|
.
LX222E10T
14-6
while ( <ORDERS> ) {
chomp;
($stock,$quan,$desc,$row,$col,$bin,$price,$store) =
split (/:/);
write PICKLIST ;
}
LX222E12T
14-7
LX222E14T
14-8
$
$%
$=
Printable lines/page
$-
14-10
# modify defaults
$old_fh = select PICKLIST;
$= = 14;
# Change variables for
$ = 'PICKLIST_NEW'; # the PICKLIST filehandle.
select $old_fh;
# Restore previous value.
...
write PICKLIST; # using PICKLIST_NEW format
...
if ($quan <= 0) {
print PICKLIST "\n** OUT OF STOCK **\n\n";
# adjust linecount:$old_fh = select PICKLIST; $- -= 3; select $old_fh;
}
LX222E20T
14-11
@######.##
$stock * $value
Result:
250
307.50
LX222E24T
14-13
left-justified
right-justified
centered
Example:
@<<<<<<<<<< @|||||||||| @>>>
scalar localtime, $title, $%
LX222E26T
Result:
Description: This is a
multi-line
paragraph.
LX222E28T
14-15
<<<<<<<<<<<<<<<<
$data
LX222E30T
Summary
Understanding report formats
Define a report format
Executing a report format
Filehandles in reports
Format names
Place holders
LX222E02T
15-1
Objectives
After completing this unit, you should be able to:
Get and set environment variables
Get network host information
Manipulate binary data
Access password data by username, ID or sequentially
Access group data by group, ID or sequentially
LX222F00T
Environment Variables
Variable data inherited by a child process from its parent
Available in Perl as the %ENV hash
Examples:
print "Hello $ENV{'USER'}\n";
chdir $ENV{HOME};
$ENV{"PATH"} = "/bin:/usr/bin:/etc:";
$ENV{IFS} = " \t\n";
Copyright IBM Corp. 1999, 2001
15-3
$$
$?
$]
$O
$T
15-5
AND 15 & 2 is 2
OR 16 | 2 is 18
XOR 15 2 is 13
<<
>>
|=
=
<<=
>>=
|
2
is
18
| 00000010
00010010
&
"X"
is
"@"
& 01011000
01000000
LX222F10T
15-6
15-7
setpwent;
print "Username Shell
Home\n";
while (@pw = getpwent) {
printf "%-8s %-10s %s\n", $pw[0], $pw[8], $pw[7];
}
endpwent;
LX222F16T
15-9
setgrent;
while (@grp = getgrent) {
print $grp[0], "\n" if $grp[3] = /\b$user\b/;
}
endgrent;
LX222F20T
15-11
($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$dst) = gmtime;
++ $mon; $year += 1900;
print "The time here is: ", scalar(localtime), "\n";
@tomorrow = localtime(time + 24*3600);
++ $tomorrow[4]; $tomorrow[5] += 1900;
LX222F22T
15-12
Summary
Get and set environment variables
Get network host information
Manipulate binary data
Access password data by username, ID or sequentially
Access group data by group, ID or sequentially
LX222F02T
16-1
Objectives
After completing this unit, you should be able to:
Run other programs from within Perl
Run programs and capture their output
Open pipes to or from other processes
Overlay the Perl program with another
LX222G00T
Run a Program
system passes its argument to the shell for execution
Syntax:
system(command-line)
Example:
system 'ls /var/spool/mail';
# run, wait for completion
system 'who >/tmp/whoout';
# run with shell redirection
system("make World >$log 2>&1 &"); # background submit
Returns 0 on success!
Copyright IBM Corp. 1999, 2001
16-3
foreach (qx/ls/) {
unlink $_;
}
($heading, @ps) = ps ;
LX222G08T
16-5
Example:
16-6
16-7
Signals
Programs on UNIX can send and receive signals
Programs receiving a signal usually exit
Common signals and their causes include:
SIGHUP Hangup. User logged out
SIGINT Interrupt. From Control-C
SIGQUIT Interrupt and write core. From Control-\
SIGTERM Terminate request. From kill <PID>
Signals are sent with kill
Syntax:
Copyright IBM Corp. 1999, 2001
16-8
# ignore hangups
# (re)store default (terminate)
$debug = 0;
$SIG{USR1} = sub {$debug = 1;}; # reference to anonymous
$SIG{USR2} = sub {$debug = 0;}; #
subroutine
LX222G16T
16-9
Summary
Run other programs from within Perl
Run programs and capture their output
Open pipes to or from other processes
Overlay the Perl program with another
LX222G02T