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

Linux, Perl - LX222VIS

Linux, Perl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

Linux, Perl - LX222VIS

Linux, Perl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 238



Linux and Perl Programming


(Course Code LX22)

Master Visuals
ERC2.1

IBM Learning Services


Worldwide Certified Material

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

Freelance is a trademark of Lotus Development Corporation in the United States, or


other countries, or both.
Microsoft, Windows, Windows NT and the Windows 95 logo are trademarks of Microsoft
Corporation in the United States and/or other countries.
UNIX is a registered trademark in the United States and/or other countries licensed
exclusively through X/Open Company Limited.
Linux is a registered trademark of Linus Torvalds in the United States, or other
countries, or both.
Other company, product, and service names may be trademarks or service marks of
others.

February 2001 Edition


The information contained in this document has not been submitted to any formal IBM test and is
distributed on an as is basis without any warranty either express or implied. The use of this information
or the implementation of any of these techniques is a customer responsibility and depends on the
customer's ability to evaluate and integrate them into the customer's operational environment. While each
item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the
same or similar results will result elsewhere. Customers attempting to adapt these techniques to their own
environments do so at their own risk.
Copyright International Business Machines Corporation 1999, 2001. All rights reserved.
This document may not be reproduced in whole or in part without the prior written permission of
IBM.
Note to U.S. Government Users Documentation related to restricted rights Use, duplication or
disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp.

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 . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Unit 2. Simple Data Types . . . . . . . . . . . . . .


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . .
Scalar Data . . . . . . . . . . . . . . . . . . . . . . . . . .
Scalar Strings . . . . . . . . . . . . . . . . . . . . . . . .
String Comparison Operators . . . . . . . . . . . . .
Additional String Operators . . . . . . . . . . . . . . .
Scalar Numbers . . . . . . . . . . . . . . . . . . . . . .
Arithmetic Operators . . . . . . . . . . . . . . . . . . .
Arithmetic Comparison Operators . . . . . . . . . .
Additional Logical Operators . . . . . . . . . . . . . .
Operator Precedence and Associativity . . . . . .
Operator Precedence and Associativity Examples
Scalar Variables . . . . . . . . . . . . . . . . . . . . . .
Scalar Assignment . . . . . . . . . . . . . . . . . . . . .
Variable Replacement in Strings . . . . . . . . . . .
Additional Assignment Operators . . . . . . . . . . .
The ++ and -- Operators . . . . . . . . . . . . . . . .
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . .
Unit 3. I/O Using Standard Input and Output
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . .
The print Operator . . . . . . . . . . . . . . . . . . . .
The printf Operator . . . . . . . . . . . . . . . . . . .
The Undefined Value . . . . . . . . . . . . . . . . . .
The Input Operator: <> . . . . . . . . . . . . . . . . .
Removing Line Delimiters: chop . . . . . . . . . .

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

Copyright IBM Corp. 1999, 2001

iii

Removing Line Delimiters: chomp


Summary . . . . . . . . . . . . . . . .
Unit 4. Flow Control .
Objectives . . . . . . . . . .
The Statement Block . .
The if/else Construct . .
The elsif Construct . . . .
The unless Construct . .
The while Construct . . .
The Default Variable: $_
while() Shortcut Using $_
The until Construct . . .
The for Construct . . . . .
The foreach Construct .
Summary . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Unit 5. Lists and Arrays . . . . . . . .


Objectives . . . . . . . . . . . . . . . . . . . .
Defining a List . . . . . . . . . . . . . . . . .
List Examples . . . . . . . . . . . . . . . . .
The Range Operator: .. . . . . . . . . . .
Arrays and Array Variables . . . . . . . .
Array Assignment . . . . . . . . . . . . . .
Single Element Access . . . . . . . . . . .
Multiple Element Access: Array Slices
Array Operators: push() and pop() . . .
Array Operators: unshift() and shift() .
Array Operators: splice() . . . . . . . . .
List Operators: reverse() . . . . . . . . . .
List Operators: sort() . . . . . . . . . . . .
Using chop() and chomp() with Arrays
Array Variable Replacement in Strings
Summary . . . . . . . . . . . . . . . . . . . .
Unit 6. Regular Expressions
Objectives . . . . . . . . . . . . . .
Regular Expression Concepts
Types of Patterns . . . . . . . .
Character Class Examples . .
Character Class Shortcuts . .
Multiple Character Patterns . .
A Sequence of Patterns . . . .
Matching Alternatives . . . . . .

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

Copyright IBM Corp. 1999, 2001

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Unit 8. Multidimensional and Associative Arrays


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Defining a Two-Dimensional List . . . . . . . . . . . . . .
Two-Dimensional Arrays . . . . . . . . . . . . . . . . . . . .
Two-Dimensional Single Element Access . . . . . . . .
Going to Three Dimensions . . . . . . . . . . . . . . . . .
Associative Arrays or Hashes . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .

8-1
8-2
8-3
8-4
8-5
8-6
8-7

Copyright IBM Corp. 1999, 2001

Initializing a Hash Variable . . .


Accessing Hash Elements . . .
Hash Operators . . . . . . . . . . .
Hash Operator Examples . . . .
Removing Hash Entries . . . . .
Defining a Hash of Lists . . . . .
Hash of Lists Access Examples
Summary . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Unit 9. User-Defined Subroutines


Objectives . . . . . . . . . . . . . . . . . . .
User-Defined Subroutines . . . . . . . .
Calling a Subroutine . . . . . . . . . . .
Returning from a Subroutine 1 . . . .
Returning From a Subroutine 2 . . . .
Private Subroutine Variables . . . . . .
Private Subroutine Variables Example
Passing Parameters to a Subroutine
A Subroutine Example . . . . . . . . . .
Creating Separate Namespaces . . .
Using Separate Namespaces . . . . .
Summary . . . . . . . . . . . . . . . . . . .

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Unit 10. File I/O . . . . . . . . . . . . . . . . .


Objectives . . . . . . . . . . . . . . . . . . . . . .
I/O Related Special Variables . . . . . . . .
Filehandles . . . . . . . . . . . . . . . . . . . . .
Opening and Closing Filehandles . . . . .
The Default Filehandles . . . . . . . . . . . .
Using Other Filehandles . . . . . . . . . . . .
Failure to Open an I/O Channel . . . . . .
Use Filehandles Example . . . . . . . . . . .
The Currently Selected Output Filehandle
Summary . . . . . . . . . . . . . . . . . . . . . .
Unit 11. Advanced Flow Control
Objectives . . . . . . . . . . . . . . . . .
Statement Modifiers . . . . . . . . . .
Logical Operators For Flow Control
Loop Modifiers: next . . . . . . . . .
Loop Modifiers: redo . . . . . . . . .
Loop Modifiers: last . . . . . . . . . .
Labelling a Statement Block . . . .
Other Uses of Labelled Blocks . .

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

Copyright IBM Corp. 1999, 2001

vi

Summary

11-10

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Unit 12. Dealing With Files and Directories


Objectives . . . . . . . . . . . . . . . . . . . . . . . . .
Checking File Permissions . . . . . . . . . . . . .
File Accessibility Conditions . . . . . . . . . . . .
File Statistics: stat . . . . . . . . . . . . . . . . . . .
The Special Underscore Filehandle . . . . . . .
Creating and Deleting Directories . . . . . . . .
Changing Directory . . . . . . . . . . . . . . . . . .
Directory Handles . . . . . . . . . . . . . . . . . . .
Using Directory Handles . . . . . . . . . . . . . . .
Renaming Files: rename . . . . . . . . . . . . . .
Dealing With Hard and Soft Links . . . . . . . .
Deleting Files: unlink . . . . . . . . . . . . . . . . .
Changing Files' Modification Times: utime . .
Changing Ownership: chown . . . . . . . . . . .
Changing File's Permissions: chmod . . . . . .
Filename Expansion Globbing . . . . . . . .
Summary . . . . . . . . . . . . . . . . . . . . . . . . .
Unit 13. Running Perl . . . . . .
Objectives . . . . . . . . . . . . . . . .
Running Perl . . . . . . . . . . . . . .
Command Line Arguments . . . .
Default Input and @ARGV . . . .
Calling Perl Explicitly . . . . . . . .
Perl Command Switches . . . . .
Perl Switches Example . . . . . . .
Writing Secure Programs . . . . .
Debugging Perl . . . . . . . . . . . .
POD Plain Old Documentation
POD Markup . . . . . . . . . . . . . .
Summary . . . . . . . . . . . . . . . .

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Unit 14. Report Generation . . . . . . . . .


Objectives . . . . . . . . . . . . . . . . . . . . . . .
Understanding Report Formats . . . . . . . .
Report Formats . . . . . . . . . . . . . . . . . . .
Defining the Report Layout . . . . . . . . . . .
A Report Example . . . . . . . . . . . . . . . . .
Executing a Report Format . . . . . . . . . . .
Changing the Currently Selected Filehandle
The Page Header Report Format . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .

14-1
14-2
14-3
14-4
14-5
14-6
14-7
14-8
14-9

Copyright IBM Corp. 1999, 2001

vii

Report Format Special Variables


Report Format Variables Example
Report Layout Placeholders . . .
Numeric Variable Placeholders .
String Variable Placeholders . . .
Multi-line Variable Placeholders .
Variable Length Placeholders . .
Summary . . . . . . . . . . . . . . . .

14-10
14-11
14-12
14-13
14-14
14-15
14-16
14-17

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Unit 15. Accessing Operating System Data


Objectives . . . . . . . . . . . . . . . . . . . . . . . . .
Environment Variables . . . . . . . . . . . . . . . .
Perl System Variables . . . . . . . . . . . . . . . .
Dealing With Binary Data . . . . . . . . . . . . . .
Manipulating Binary Data . . . . . . . . . . . . . .
Obtaining Hostname Information . . . . . . . . .
Accessing Password Info by Name or ID . . .
Password File Sequential Access . . . . . . . .
Accessing Group Info by Name or ID . . . . . .
Group File Sequential Access . . . . . . . . . . .
Time Related Functions . . . . . . . . . . . . . . .
Summary . . . . . . . . . . . . . . . . . . . . . . . . .

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

. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .

Unit 16. Running External Programs . . . . . .


Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . .
Run a Program . . . . . . . . . . . . . . . . . . . . . . .
Run a Program Without Shell Interaction . . . . .
Run a Program and Capture Output . . . . . . . .
Creating Pipes to Other Programs . . . . . . . . . .
Run a Program Overlaying the Current Program
Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dealing With Signals . . . . . . . . . . . . . . . . . . .
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . .

16-1
16-2
. 16-3
. 16-4
. 16-5
. 16-6
. 16-7
. 16-8
. 16-9
16-10

. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .

Copyright IBM Corp. 1999, 2001

viii

Course Presentation Material Overview


Included in this package are landscape, black and white paper copies of each of the
student visuals included in the Student Notebook. The paper copies are to be used to
reproduce overhead transparencies required to teach the course. It is recommended
that black-on-clear transparencies be used to reproduce the package.
In addition to the student visuals, a welcome visual SHOULD be included. To ensure
that each student is attending the correct course for which they originally enrolled, the
welcome visual should be used to provide the student with the course name and course
code upon entering the classroom.
It is advised that upon checking out the classroom prior to the start of class, there be
two overhead projectors in the classroom. This will guarantee that there is a working
overhead projector available at all times for the duration of the class.
The paper copies and the transparencies created from the paper copies are the property
of IBM. By way of protecting our intellectual properties, neither the paper copies nor the
transparencies should be given to anyone other than a course certified instructor. The
copies are not to be used for any purpose other than teaching the course. The security
of this package and the products created as a result of this package are the
responsibility of the course certified instructor.

Copyright IBM Corp. 1999, 2001

ix

Unit 1. Overview

Copyright IBM Corp. 1999, 2001

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

The Usability of Perl


The original aims were:
 Help the UNIX user with common tasks that are too complex or
nonportable for the shell
 Assist the UNIX user with tasks that are not worth the effort of
writing a C program
Over the years, Perl has grown into a sophisticated,
general-purpose, cross-platform, programming language:
 Perl is a superset of awk, sed and the UNIX shells
 It also takes features from many other languages and UNIX tools
Copyright IBM Corp. 1999, 2001

Perl is available on a wide range of platforms: most programs


written in Perl run unchanged on all platforms
LX222104T

1-3

Availability and Support


The Perl homepage is http://www.perl.com
Perl is free and runs on most UNIX-like systems and many non-UNIX
systems including MS-DOS, Windows 95/98 & NT, VMS, MacOS,
OS/2, OS/400 and OS/390
The Comprehensive Perl Archive Network http://www.perl.com/CPAN/
has
 Source code for Perl and additional modules
 Binaries of Perl for some platforms
Several environments supply Perl as standard
Copyright IBM Corp. 1999, 2001

Support was originally available only from newsgroups, mailing-lists


and web sites
Commercial support now also available
LX222106T

1-4

Elementary Perl Ideas


Start Perl program files with #!/usr/bin/perl
 On Linux, make the file executable
$ chmod +x myprog.pl
 On Windows, call the Perl interpreter
C:>perl myprog.pl
 or associate the .pl extension with PERL.EXE
Perl code is free format, whitespace is ignored:
{ and } group statements
Copyright IBM Corp. 1999, 2001

; 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

Copyright IBM Corp. 1999, 2001


1-6

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

Copyright IBM Corp. 1999, 2001


1-7

Unit 2. Simple Data Types

Copyright IBM Corp. 1999, 2001

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

Perl automatically converts between string and number as required LX222204T

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'
#

exception: \ protects '


exception: \ protects \

Copyright IBM Corp. 1999, 2001

 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

String Comparison Operators


Comparison
Equal

Representation
eq

Not Equal

ne

Less than

lt

Greater than

gt

Less than or equal to

le

Greater than or equal to

ge
LX222208T

Copyright IBM Corp. 1999, 2001


2-5

Additional String Operators


Concatenation operator: .
"hello"."world"

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

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


2-8

Arithmetic Comparison Operators


Comparison
Equal

Representation
==

Not equal

!=

Less than

<

Greater than

>

Less than or equal to

<=

Greater than or equal to

>=
LX222216T

Copyright IBM Corp. 1999, 2001


2-9

Additional Logical Operators


&& and True if all expressions are true
12 > 2 && "A" lt "Z"
12 > 2 and "A" gt "Z"
|| or

True if any expression is true


1 < 2 or 2 < 3
1 > 2 || 2 < 3
1 > 2 or 2 > 3

! not

# true
# false
# true (1 < 2)
# true (2 < 3)
# false

Negate a logical expression

Copyright IBM Corp. 1999, 2001

! ("A" gt "Z")
not ("A" lt "Z")

# true
# false

The symbol and word version differ only in precedence

LX222218T

2-10

Operator Precedence and Associativity


Precedence determines the order of evaluation of operators
 Operators with higher precedence are evaluated before those with
lower
1 + 2 * 3
1 / 2 + 3

is
is

1 + (2 * 3)
(1 / 2) + 3

# 7
(not 9)
# 3.5 (not 1/5)

Associativity determines the order of evaluation of operators with the


same precedence.
Copyright IBM Corp. 1999, 2001

 Operators with left associativity evaluate left to right


 Operators with right associativity evaluate right to left
3 + 1 - 2
3 ** 1 ** 2

is
is

(3 + 1) - 2
# left associative
3 ** (1 ** 2) # right associative
LX222220T

2-11

Operator Precedence and Associativity


Examples
Example:
1 + 5 * 6;
56 / 14 / 2;
3 ** 4 ** 5;
"y" . "n" x 3;
9 + 2 x 3;
Use parentheses for clarity!
LX222222T

Copyright IBM Corp. 1999, 2001


2-12

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

Copyright IBM Corp. 1999, 2001

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

Variable Replacement in Strings


Double-quoted strings are scanned for scalar variables
When a variable is found, it is replaced with its current value
Example:

Copyright IBM Corp. 1999, 2001

$a="hello there $b"


$var = "Mon";
$varday = "wrong";
$out = "Today is $varday";
$out = "Today is ${var}day";
$out2 = "Today is $var"."day";
$out3 = "Today is " . $var . "day";
$var = "Tues";

#
#
#
#

Today
Today
Today
Today

is
is
is
is

wrong
Monday
Monday
Monday
LX222228T

2-15

Additional Assignment Operators


Binary, String and Numeric Operators can be combined with
assignment
Example:
$g += 11;
$e *= 3;
$str .= "a";

# same as $g = $g + 11;
# same as $e = $e * 3;
# same as $str = $str . "a";

You can also use:


-=

/=

%=

**=

x=

&&=

||=

Copyright IBM Corp. 1999, 2001

LX222230T

2-16

The ++ and -- Operators


Autoincrement and autodecrement operators
Syntax:
++$a;
$a++;
--$a;
$a--;

#
#
#
#

increment
increment
decrement
decrement

before use
after use
before use
after use

Example:

Copyright IBM Corp. 1999, 2001

$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

Copyright IBM Corp. 1999, 2001


2-18

Unit 3. I/O Using Standard Input and Output

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


3-2

The print Operator


Prints its comma separated list of arguments
The default destination is STDOUT
Syntax:
print($arg1, $arg2, $arg3)
Example:
print "Hello World!\n"; # list of one item
print 'say hello ', 'say goodbye';
print("\n" x 30, '-' x 80, "\n");
print $var1, $var2;
Copyright IBM Corp. 1999, 2001

LX222304T

3-3

The printf Operator


Provides formatted output
The first argument is a string specifying the number and format of
the remaining parameters
Syntax:
printf("format", arg1, arg2, arg3, ...)
Example:
printf "%10s %14.4f %e\n", $id, $val, $cnt;
printf("%-32s", $desc);
printf $fmt, $name, $phone, $mobile, $email;
Copyright IBM Corp. 1999, 2001

LX222306T

3-4

The Undefined Value


An unassigned variable has an undefined value
Usually represented as a null string or zero
Explicitly represented by undef
$x = '';
# the null string - undef
$y = undef; # the same explicitly
Can be tested for by the defined() function
undef is logically False
The perl command line switch -w enables warnings on the use of
uninitialized variables
Copyright IBM Corp. 1999, 2001

#!/usr/bin/perl -w
print 2 * $x;
# output: 0 and the warning message:# Use of uninitialized value at - line 1.
LX222308T

3-5

The Input Operator: <>


The <> operator reads data from a filehandle
Syntax:
<FILEHANDLE>
Example:
print "Enter elevation: ";
$a = <STDIN> ;
$line = <> ;
If no filehandle is specified, <>:
Copyright IBM Corp. 1999, 2001

 reads from files on the command line


 or STDIN if no files are specified
LX222310T

3-6

Removing Line Delimiters: chop


Data read from a file will contain the line delimiter
chop removes the last character from a string variable
Syntax:
chop( variable )
Example:
$x = <STDIN>;
chop $x;
Copyright IBM Corp. 1999, 2001

$delim = chop( $x = <STDIN> ); # all together!


LX222312T

3-7

Removing Line Delimiters: chomp


Data read from a file will contain the line delimiter
chomp removes the record delimiter from a string variable, if present
Syntax:
chomp( variable )
Example:

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


3-9

Unit 4. Flow Control

Copyright IBM Corp. 1999, 2001

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

The Statement Block


A statement block is a list of statements surrounded by curly braces
The statements are executed sequentially
Syntax:
{
first_statement ;
second_statement ;
third_statement ;
}
Copyright IBM Corp. 1999, 2001

LX222404T

4-3

The if/else Construct


The basic decision-making control structure
Syntax:
if (test_expression) {
# statements executed if test_expression is true
}
else {
# optional else clause
# statements executed if test_expression is false
}
Example:
Copyright IBM Corp. 1999, 2001

if ( $month < 13 ) {
print "A possible month of the year" ;
}
else {
print "Invalid month ($month) > 12\n";
}
LX222406T

4-4

The elsif Construct


Provides for multiple test conditions
Syntax:
if
(test_expression1) {statements_1}
elsif (test_expression2) {statements_2}
else
{statements_3}
Example:

Copyright IBM Corp. 1999, 2001

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

The unless Construct


When you want to execute only the else part of an if/else
Execute the statement block if the test is false
Syntax:
unless (test_expression) {statement_block}
Example:
unless ($month > 0 && $month < 13) {
print "Cannot be a month of the year" ;
}
LX222410T

Copyright IBM Corp. 1999, 2001


4-6

The while Construct


Execute a statement block while a condition is true
Syntax:
while (test_expression) {statements}
do {statements} while (test_expression)
Example:
while ( $x < 10 ) {
$x ++ ;
}
Copyright IBM Corp. 1999, 2001

do {
print $x -- ;
sleep 1;
} while ( $x >= 0 );
LX222412T

4-7

The Default Variable: $_


A special global variable
Used by many functions if no other variable specified:
print;
chop;
chomp;

# print $_;
# chop $_;
# chomp $_;
LX222414T

Copyright IBM Corp. 1999, 2001


4-8

while() Shortcut Using $_


When the input operator <> is the only condition in a while()
The input value is assigned to $_
Example:
while ( <STDIN> ) {
chomp;
print;
}
is the same as:
Copyright IBM Corp. 1999, 2001

while ( defined($_ = <STDIN>) ) {


chomp $_;
print $_;
}
LX222416T

4-9

The until Construct


A variation on the while statement
Execute a statement block until a condition is true
Syntax:
until (test_expression) {statement_block}
do {statement_block} until (test_expression);
Example:
until ( $x <= 0 ) {
$x--;
}
Copyright IBM Corp. 1999, 2001

LX222418T

4-10

The for Construct


A loop with initialization, test and increment expressions
Syntax:
for (init_exp; test_exp; incr_exp) {statements}
Example:
for ($c = 100; $c >= 0; $c -= 5) {
printf "%3dC is %3dF\n", $c, $c * 9/5 + 32;
}
Copyright IBM Corp. 1999, 2001

LX222420T

4-11

The foreach Construct


Execute a block for each element of a list of values
Sets a loop variable to each value in turn
Syntax:
foreach $item (list) {statements}
Example:
foreach $flag ("red", "white", "blue") {
print $flag;
}
Copyright IBM Corp. 1999, 2001

If omitted, the loop variable defaults to $_


foreach ("red", "white", "blue") {
print;
}
LX222422T

4-12

Summary
 Statement blocks
 if/else statement
 elsif branch
 the unless variation
 while and until statements
 for statement
 foreach statement
LX222402T

Copyright IBM Corp. 1999, 2001


4-13

Unit 5. Lists and Arrays

Copyright IBM Corp. 1999, 2001

5-1

Objectives
After completing this unit, you should be able to use:
 Lists
 Arrays
 Array variables
 Array operators
LX222500T

Copyright IBM Corp. 1999, 2001


5-2

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

Copyright IBM Corp. 1999, 2001


5-3

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

The Range Operator: ..


Creates a list of all values between its operands
Syntax:
(1 .. 10)
("A" .. "E")

# (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

Copyright IBM Corp. 1999, 2001


5-5

Arrays and Array Variables


An array is a named list
Array variables are defined with a leading @
Array and scalar variables have separate namespaces
@arrayname refers to the whole array
Arrays are created automatically when referenced
Arrays grow dynamically as required
Individual elements are accessed by number
 Starting at 0
LX222510T

Copyright IBM Corp. 1999, 2001


5-6

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

Copyright IBM Corp. 1999, 2001


5-7

Single Element Access


Individual elements are accessed with a $ prefix and a subscript (or
index) in brackets
Syntax:
$arrayname[ index ]
Example:

Copyright IBM Corp. 1999, 2001

@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

Multiple Element Access: Array Slices


Multiple elements of an array can be accessed at once
This is called taking an array slice
Syntax:
@arrayname[subscript, subscript, ...]
Example:
@nums = (5, 6, 7, 8, 9);
@revd = @nums[4,3,2,1];
@nums[1, 3] = (2, 2) ;
@nums[2, 4] = (4, 3) ;

# (9, 8, 7, 6)
# (5, 2, 7, 2, 9)
# (5, 2, 4, 2, 3)

Copyright IBM Corp. 1999, 2001

LX222516T

5-9

Array Operators: push() and pop()


Add or remove elements at the end of an array
Syntax:
push(@arrayname, list, of, values)
pop(@arrayname)
Example:

Copyright IBM Corp. 1999, 2001

@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

Array Operators: unshift() and shift()


Add or remove elements at the start of an array
Syntax:
unshift(@arrayname, list, of, values)
shift(@arrayname)
Example:

Copyright IBM Corp. 1999, 2001

@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

Array Operators: splice()


Add or remove elements anywhere in an array
Syntax:
splice(@arrayname, offset, remove, list, of, values)
Example:

Copyright IBM Corp. 1999, 2001

@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

List Operators: reverse()


Returns a copy of its argument list in reverse order
Syntax:
reverse(list)
reverse @array
Example:
@forward = (10,20,30,40);
@backward = reverse(@forward);
@countdown = reverse 0..10;

(40,30,20,10)
LX222524T

Copyright IBM Corp. 1999, 2001


5-13

List Operators: sort()


Returns a copy of its argument list in ascending character set
sequence
Syntax:
sort(@array)
sort(list)
Example:

Copyright IBM Corp. 1999, 2001

@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

Using chop() and chomp() with Arrays


chomp removes the end of record marker from each element of an array
chop removes the last character from each element of an array
Syntax:
chomp( @array )
chop( @array )
Example:

Copyright IBM Corp. 1999, 2001

@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

Array Variable Replacement in Strings


Double-quoted strings are scanned for array variables
When found, a variable is replaced with its current value
Example:

Copyright IBM Corp. 1999, 2001

@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

print "Email address: info\@ibm.com\n"; # escape literal @


LX222530T

5-16

Summary
 Lists
 Arrays
 Array variables
 Array operators
LX222502T

Copyright IBM Corp. 1999, 2001


5-17

Unit 6. Regular Expressions

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


6-2

Regular Expression Concepts


Regular Expressions are used to describe a string of characters
Perl's match operator uses regular expressions to search for
matching text
The substitute operator uses regular expressions to select the text
to be replaced
A regular expression is made up of patterns of ordinary characters
and special metacharacters
Regular expressions are usually shown in slashes: /patterns/

Copyright IBM Corp. 1999, 2001

Perl's regular expressions are similar to those of other Linux


programs
LX222604T

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

To match metacharacters for example . [ ]


 protect them with a backslash: \. \[ \]
LX222606T

6-4

Character Class Examples


/[AEIOU]/

an uppercase English vowel

/[2468]/

a single, non-zero, even digit

/[0-5]/

define range using hyphen

/[789-]/

hyphen first or last to match a hyphen

/[a-z]/

lowercase alphabetic

/[0-9]/

initial caret specifies a negated character class

/[a-z]/

NOT a lower case alphabetic English letter

/[A-Za-z0-9_]/

an alphanumeric - multiple ranges are OK

Copyright IBM Corp. 1999, 2001

LX222608T

6-5

Character Class Shortcuts


Perl provides a set of shortcuts for character classes
Syntax:
\d
\D
\w
\W
\s
\S

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]

Shortcuts are locale aware if locales are available and configured


Copyright IBM Corp. 1999, 2001

Example:
if ( /\d/ ) { print "Found a digit!"; }
LX222610T

6-6

Multiple Character Patterns


We usually need to match more than one character
There are four ways of grouping patterns to match multiple
characters
 Sequence
 Alternation
 Multipliers
 Parentheses as memory and for precedence
Copyright IBM Corp. 1999, 2001

We will look at each in turn


LX222612T

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:

Copyright IBM Corp. 1999, 2001

?
*
+
{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

Copyright IBM Corp. 1999, 2001


6-11

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

Parentheses as Memory Example


Regular Expression is
/D(.)E(k.)F\2G\1H/

Copyright IBM Corp. 1999, 2001

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$/

match pattern at start of string


match pattern at end of string

Example:

Copyright IBM Corp. 1999, 2001

/\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

xz, xyz, xyyz, xyyyz, xyyyyz, etc.


"", xyz, xyzxyz, xyzxyzxyz, etc.
t anywhere OR v at end of string
EITHER t OR v at end of string
LX222628T

6-15

The Match Operator


Returns true or false depending on whether its regular expression
matches a string
The default match target is $_
Syntax:
/regular_expression/
m#regular_expression#
m{regular_expression}
Example:
Copyright IBM Corp. 1999, 2001

m/From: / ;
/From: / ;
m#/.*/(.*)# ;
m{From: (.*)} ;
LX222630T

6-16

The Pattern Binding Operators


Specifies the target of a match operation
Syntax:
$variable = /reg_expr/
$variable ! /reg_expr/
Example:
if ( $answer = /[Yy]/ ) { ... }
Copyright IBM Corp. 1999, 2001

$name = /(\w+)\s+((\w\.?)\s+)?(\w+)/;
while ( $answer ! /[YyNn]/ ) {
print "Enter 'Y'es or 'N'o: ";
chomp($answer = <STDIN>);
}
LX222632T

6-17

The Substitution Operator


Replaces a string matched with a regular expression
The default target is $_
The traditional delimiters are /// any other single character or two
pairs of brackets can be used
Syntax:
s/pattern/replacement_string/
Example:

Copyright IBM Corp. 1999, 2001

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

Match and Substitution Modifiers


Ignore case
if ( /y/i ) { ... }

# /[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

Treat string as multiple lines: /$ match after/before embedded newlines


@caps = /([A-Z])/mg; # All capital letters at start of a line
Treat string as a single line: . matches \n
/(.*);$/s;

# store all text up to ; at end of line


LX222636T

6-19

Substitution Examples
$_ = "a long, long, long time ago";
s/long/short/;

# "a short, long, long time ago"

s/long/MEDIUM/g;

# "a short, MEDIUM, MEDIUM time ago"

$var = ' TIME';


s/, MEDIUM/$var/; # "a short TIME, MEDIUM time ago"
$_ = s/time/period/gi; # "a short period, MEDIUM period ago"
LX222638T

Copyright IBM Corp. 1999, 2001


6-20

Matching Operator Special Variables 1


Special read-only variables set during matching
Useful for debugging!
$

text before the match

$&

the matched text

$'

text after the match

Example:
$_ = "this is a simple sentence" ;
/si.*le/ ;
Copyright IBM Corp. 1999, 2001

print $;
print $&;
print $';

# "this is a "
# "simple"
# " sentence"
LX222640T

6-21

Matching Operator Special Variables 2


The patterns \1, \2, ... are only available within the regular expression
Special read-only variables $1, $2, ... are available outside the
regular expression with the same content
Example:
$line = m/From: (.*)/ ;
$sender = $1 ;
Parenthesized patterns are also returned by matching if the
destination expects a list
Copyright IBM Corp. 1999, 2001

$string = "this is a simple sentence" ;


@words = ( $string = /(\w+)/g ) ;
LX222642T

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 ?

Copyright IBM Corp. 1999, 2001

/(t.*?s)/ ; # $1 is 'this'
m#<b>(.*?)</b>#sig ; # only bold phrases
LX222644T

6-23

Regular Expression Metacharacter Summary


Metacharacters are symbols that have special meaning in a regular
expression
[ ]

\ 

{ }

()

The regular expression delimiters are also special


Protect all these characters with \ to match themselves literally
LX222646T

Copyright IBM Corp. 1999, 2001


6-24

Summary
 Concepts of Regular Expressions
 Single-character patterns
 Grouping patterns
 Anchoring patterns
 Pattern precedence
 The matching and substitution operators
LX222602T

Copyright IBM Corp. 1999, 2001


6-25

Unit 7. String and Array Processing

Copyright IBM Corp. 1999, 2001

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:

Copyright IBM Corp. 1999, 2001

Create lists from strings


Create strings from lists
Apply expressions to members of a list
Define your own sort order
LX222700T

7-2

Generalized Quotes
Operators that provide alternative string delimiters
Syntax:
q/single quoted string/
qq{double quoted string}
Example:

Copyright IBM Corp. 1999, 2001

$string
$string
$string
$string
$string
$string

=
=
=
=
=
=

'This isn\'t Bob\'s car!';


q/This isn't Bob's car!/;
'C:\\windows\\system\\viewers\\file';
q/c:\windows\system\viewers\file/;
"\"Help!\" $name cried.";
qq("Help!" $name cried.);
LX222704T

7-3

The here Document


Another way of quoting text especially useful for large strings
Syntax:
<<DELIMITER
string
DELIMITER
Example:

Copyright IBM Corp. 1999, 2001

print <<EOS1, <<'EOS2' ;


$date
Dear $name,
EOS1
Single quoted string: no $variable interpolation
EOS2
LX222706T

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

Locating a Substring Example


$pos = index("hello, hello, hello!", "e");

# 1

$substr = " ";


$pos = index("hello, hello, hello!", $substr); # 6
$pos = index("hello, hello, hello!", "e", 2);

# 8

$pos = rindex("hello, hello, hello!", "e");


# 15
$pos = rindex("hello, hello, hello!", "e", 6); # 8
$pos = index("hello, hello, hello!", "X");

# -1

Copyright IBM Corp. 1999, 2001

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

Alphabetic Case Operators


Return a copy of the source string with (possibly) altered case
Syntax:
lc( string )
lcfirst( string )
uc( string )
ucfirst( string )
Example:

Copyright IBM Corp. 1999, 2001

print lc $code ;
$key = uc $key ;
print ucfirst lc $name ;
print uc ; # use $_
The default source is $_
LX222716T

7-9

The Translation Operator


Do multiple character replacements at once
The default target is $_
 Use the binding operator = to specify another target
Returns the number of characters replaced or deleted
Syntax:
tr/old_char_list/new_char_list/cds
y/old_char_list/new_char_list/cds
Example:
Copyright IBM Corp. 1999, 2001

$_ = 'hello cruel world' ;


tr/hcw/xvy/ ;
# 'xello vruel yorld'
LX222718T

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

Copyright IBM Corp. 1999, 2001


7-11

The map() Operator


Evaluate an expression or a block for each item in a list
Returns a list of the return values from the block
Sets $_ to the current element
Syntax:
map expression, list
map {block} list
Example:

Copyright IBM Corp. 1999, 2001

@decimal = (1.1, 2.22, 3.333, 4.4444);


@integer = map(int, @decimal);
# (1,2,3,4)
@small_nums = map {if($_<3){$_}} @decimal; # (1.1, 2.22)
@squares = map $_**2, 0 .. 100; # 0,1,4,9,16,25, ...
LX222722T

7-12

The grep() Operator


Evaluate an expression or a block for each item in a list
If the expression or block evaluates to true, add the item to the
output list
Syntax:
grep expression, list
grep {block} list
Example:

Copyright IBM Corp. 1999, 2001

@odds = grep /[13579]$/, 0 .. 100; # 1,3,5 ... 97,99


@odds = grep {$_ % 2} 0 .. 100;
@div3 = grep !($_ % 3), 0 .. 100; # 0,3,6,9 ... 93,96,99
if ( grep /chris/, @users ) { ... }
grep tr/a-z/A-Z/, @codes;
LX222724T

7-13

Breaking a String Apart


split() breaks a string into a list of strings
 using a regular expression to match the delimiter
Syntax:
split(/reg_expr/, string, limit)
Example:
$line = "joey:!:222:20::/home/joey:/usr/bin/ksh" ;
@fields = split(/:/ , $line) ;
Copyright IBM Corp. 1999, 2001

$_ = "root
391
1 0 Mar14 ?
($user, $pid, undef) = split;
($user, $pid, undef) = split /\s+/, $_, 3;

00:00:00 lpd";

LX222726T

7-14

The Quote Words Operator: qw()


One of the generalized quoting operators
Returns a list of whitespace-separated words
Used to simplify writing of lists
Syntax:
qw(STRING)
Works like:
split /\s+/, 'STRING';
Example:
Copyright IBM Corp. 1999, 2001

@nums = qw/zero one two three four five six


seven eight nine/;
LX222728T

7-15

Joining a List Together


Return the string created by joining a list with a specified delimiter
Syntax:
join(delimiter, list)
Example:
$line = "joey:!:222:20::/home/joey:/usr/bin/ksh" ;
@fields = split(/:/ , $line) ;
$newline = join(":" , @fields) ;

Copyright IBM Corp. 1999, 2001

print join("\n", @INC), "\n";


print join "\n", @INC, '';

# needs a trailing \n
# append a dummy (null) value

$domain = 'training.uk.ibm.com' ;
print join '.', reverse split /\./, $domain ;
LX222730T

7-16

The sort() Operator


The sort order can be defined by a user-supplied block or subroutine
The block or subroutine should return less than, equal to, or greater
than zero
 depending on the comparison of two values
Syntax:
sort list
sort { statements } list
sort subroutine list
The comparison operators are typically used:
Copyright IBM Corp. 1999, 2001

<=>

numeric comparison (spaceship) operator

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

Copyright IBM Corp. 1999, 2001

@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:

Create lists from strings


Create strings from lists
Apply expressions to members of a list
Define your own sort order

Copyright IBM Corp. 1999, 2001

LX222702T

7-19

Unit 8. Multidimensional and Associative Arrays

Copyright IBM Corp. 1999, 2001

8-1

Objectives
After completing this unit, you should be able to use:
 Multidimensional arrays
 Associative arrays or hashes
 Hash operators
LX222800T

Copyright IBM Corp. 1999, 2001


8-2

Defining a Two-Dimensional List


Perl "flattens" multiple lists into one:
( 'a', (1,2), 'b', (3,4), ('c', (5,6)) )
is treated as ('a',1,2,'b',3,4,'c',5,6)
A two-dimensional list is a normal list, where each element is
another list enclosed in brackets
Example:
(

Copyright IBM Corp. 1999, 2001

['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']

Adding and removing elements:

Copyright IBM Corp. 1999, 2001

push(@students, ['Pebbles', 'F', 'P', 'principal engineer']);


@newone = ('Bam Bam', 'M', 'B', 'senior programmer');
push(@students, [ @newone ] );
@fred = @{ shift @students };
LX222806T

8-4

Two-Dimensional Single Element Access


Individual elements are accessed with both subscripts.
Syntax:
$arrayname[row][column]
Example:
 Changing array elements:
$students[2][2] = 'P' ;
 Printing an array element:
print $student[3][0] ;

# Barney

Copyright IBM Corp. 1999, 2001

LX222808T

8-5

Going to Three Dimensions


Assignment:
@students = (
['Fred',
['Wilma',
['Betty',
['Barney',
) ;

'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

print "$students[0][0] got a $students[0][2][1]";


$students[3][2][1] = 'C';
push @{ $students[3][2] }, 'D';
# ['Barney', 'M', ['P','C','D'], 'systems engineer']
LX222810T

8-6

Associative Arrays or Hashes


An hash holds scalar data indexed by some other scalar value
 The index or key need not be numeric, but must be unique
 The number of elements is limited only by your system
Hashes used to be called associative arrays

Copyright IBM Corp. 1999, 2001

key
Fred
Wilma
Betty
Barney

value
systems analyst
programmer
network analyst
systems engineer
LX222812T

8-7

Initializing a Hash Variable


From key/value pairs in a normal list:
%hash = ( 'key1', 'value1', 'key2', 'value2' );
From a list with alternative delimiters:
%students =
Fred
Wilma
Betty
Barney
) ;

(
=>
=>
=>
=>

'systems analyst' ,
'programmer' ,
'network analyst' ,
'systems engineer'

Copyright IBM Corp. 1999, 2001

From other hashes:


%workers = %students;
LX222814T

8-8

Accessing Hash Elements


Syntax:
$hashname{ key }
Adding and changing hash values:
$students{ 'Wilma' } = 'Operator';
$students{ 'Pebbles' } = 'Trainee';
$students{ 'Wilma' } = 'Supervisor';
Printing hash values:
Copyright IBM Corp. 1999, 2001

print $students{ 'Barney' };


LX222816T

8-9

Hash Operators
keys() returns a list of all the keys in a hash
Syntax:
keys(%hash)

values() returns a list of all the values in a hash


Syntax:
values(%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

Hash Operator Examples


%nums = (0=>'zero', 1=>'one', 2=>'two', 3=>'three', 4=>'four',
5=>'five', 6=>'six', 7=>'seven', 8=>'eight', 9=>'nine');
print join ',', keys(%nums);
# 0,1,2,3,4,5,6,7,8,9
print join ',', values(%nums);
# zero,one,two,three,four,five,six,seven,eight,nine
foreach $key (split '', 112) {
print "$nums{ $key } ";
}
# "one one two "

Copyright IBM Corp. 1999, 2001

foreach $key (sort keys %nums ) {


print "for key $key the value is $nums{$key}\n"
}
while (($k, $v) = each(%nums)) {
print "Key is $k and value is $v \n";
}
LX222820T

8-11

Removing Hash Entries


delete removes the key-value pair referenced by the key
 and returns the value
Syntax:
delete $arrayname{key}
Example:
delete $students{'Pebbles'};
$vacancy = delete $students{"Bambam"};
defined tests whether the value is defined
Copyright IBM Corp. 1999, 2001

exists tests whether a hash contains the key


if (exists $students{'Barney'}) { ... }
LX222822T

8-12

Defining a Hash of Lists


A hash can have a list as its value
Example:
%students =
Fred
Wilma
Betty
Barney
) ;

(
=>
=>
=>
=>

['M',
['F',
['F',
['M',

'B',
'A',
'P',
'P',

'systems analyst'] ,
'operator'] ,
'network analyst'] ,
'systems engineer']
LX222824T

Copyright IBM Corp. 1999, 2001


8-13

Hash of Lists Access Examples


Changing array values:
$students{'Wilma'}[2] = 'Backup Admin';
Printing an array value:
print $students{'Barney'}[2];

# systems engineer

Adding new values:


$students{'Pebbles'} = ['F', 'P', 'principal engineer'];
A hash of hashes:
Copyright IBM Corp. 1999, 2001

%students = (Wilma => { gender => 'F',


education => 'A', job => 'operator'},
...);
print $students{'Wilma'}{'job'};
LX222826T

8-14

Summary
 Multidimensional arrays
 Associative arrays or hashes
 Hash operators
LX222802T

Copyright IBM Corp. 1999, 2001


8-15

Unit 9. User-Defined Subroutines

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


9-2

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:

Copyright IBM Corp. 1999, 2001

sub print_line {
print '-' x 80, "\n";
}
LX222904T

9-3

Calling a Subroutine
Syntax:
&subname
subname()
subname
Example:
&print_line;
print_line();
print_line;

# original (Perl4) format


# & optional in Perl5 with parentheses
# () optional in Perl5 if sub predefined
LX222906T

Copyright IBM Corp. 1999, 2001


9-4

Returning from a Subroutine 1


The return statement exits a subroutine immediately
With an optional return value
Syntax:
return (expression)
Example:

Copyright IBM Corp. 1999, 2001

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

Returning From a Subroutine 2


The return value of a subroutine is:
 the value of the return statement, or
 the value of the last expression evaluated
Example:
sub mymax {
if ($a >= $b) {
else { $b; }
}
Copyright IBM Corp. 1999, 2001

sub mypow {

$a; }

$a ** $b; }
LX222910T

9-6

Private Subroutine Variables


Private variables can be created in a user subroutine with the my
and local operators
Syntax:
my ( $var )
local ( $var1, @array, %hash )
Example:

Copyright IBM Corp. 1999, 2001

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

Private Subroutine Variables Example


print $m, $l;
mysub1();
print $m, $l;

# 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

Passing Parameters to a Subroutine


Parameters are passed to subroutines as a list
Example:
mymax( @scores );
Subroutines receive their parameters in the special array @_

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001

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

Creating Separate Namespaces


A package statement declares a separate namespace
The declaration has the same scope as my()
Example:

Copyright IBM Corp. 1999, 2001

package utils;
sub min {
$min = shift;
foreach (@_) { if ($_ < $min) { $min = $_ } }
$min;
}
sub max {
$max = shift;
foreach (@_) { if ($_ > $max) { $max = $_ } }
$max;
}
LX222920T

9-11

Using Separate Namespaces


Prefix a symbol name with the package to refer to names in other
namespaces
Example:
print utils::max( 2, 22, -3, 10, 16);
print utils::min( 2, 22, -3, 10, 16);
print "The last value of max was $utils::max\n";
LX222922T

Copyright IBM Corp. 1999, 2001


9-12

Summary
 Define subroutines
 Use user-defined subroutines
 Return from subroutines
 Pass variables to subroutines
 Use packages
LX222902T

Copyright IBM Corp. 1999, 2001


9-13

Unit 10. File I/O

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


10-2

I/O Related Special Variables


Several special variables affect input and output:
$\
$,
$"
$|
$/
$.

Output Record Separator, default: undef


Output Field Separator, default: undef
Interpolated List Separator, default " "
Autoflush Output, default 0
Input Record Separator, default: "\n"
Input Line Number

Example:

Copyright IBM Corp. 1999, 2001

$| = 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

Copyright IBM Corp. 1999, 2001


10-4

Opening and Closing Filehandles


Filehandles must be open before use and should be closed after use
Syntax:
open(FILEHANDLE, "filename")
close(FILEHANDLE)
The filename is checked for characters which control the open mode
Example:

Copyright IBM Corp. 1999, 2001

open(INFILE, $filename) ;
open PASSWD, "<$passwd" ;
unless ( open OUTFILE, ">$outfile" ) { ... }
if ( open(LOGFILE, ">> $logfile") { ... }
close(LOGFILE);
close PASSWD;
LX222A08T

10-5

The Default Filehandles


We have already seen that:
 the angle operator <> is used for input
 print and printf are for output
The default filehandles are:
 files on the command-line or STDIN for <>
 STDOUT for print and printf
These defaults can be changed within the program
The standard filehandles can be redirected from the command
prompt
Copyright IBM Corp. 1999, 2001

 avoiding the need for opening files in the program


$ myprog <data.in >data.out 2>>error.log
LX222A10T

10-6

Using Other Filehandles


Syntax:
print(FILEHANDLE list)
printf(FILEHANDLE "format", list)
<FILEHANDLE>
Example:
print(STDERR "Starting ...");
print LOGFILE "starting at ", scalar localtime, "\n" ;
Copyright IBM Corp. 1999, 2001

while ( <INFILE> ) { ... }


LX222A12T

10-7

Failure to Open an I/O Channel


Always test the return status of open()
warn is a convenient way to print an error message
die is a convenient way to exit gracefully with an error
Syntax:
die("message")
warn("message")
Example:

Copyright IBM Corp. 1999, 2001

unless (open MYFILE, ">$myfile) {


die "Sorry, cannot create $myfile: $!\n" ;
}
open(MYFILE,">$myfile") ||
die "Sorry, cannot create $myfile: $!\n" ;
LX222A14T

10-8

Use Filehandles Example


$invent = 'filea';
$report = 'reporta';
open(INVENTORY, $invent) ||
die "cannot open $invent: $!\n";
open REPORT, ">$report" or
die "cannot create $report: $!\n";
while ( <INVENTORY> ) {
print REPORT &calc($_);
}
Copyright IBM Corp. 1999, 2001

close(REPORT);
close(INVENTORY);
LX222A16T

10-9

The Currently Selected Output Filehandle


The default output filehandle at startup is STDOUT
select can specify another filehandle
select returns the currently selected output filehandle
Syntax:
select FILEHANDLE
Example:
select LOG;

# LOG is the default output

Copyright IBM Corp. 1999, 2001

$csf = select REPORT; # now REPORT is the default output


print $v;
# to REPORT
select $csf;
# restore the previous value
LX222A18T

10-10

Summary
 Use more print operations
 Open and close filehandles
 Read and write user-defined filehandles
 Select the default output filehandle
LX222A02T

Copyright IBM Corp. 1999, 2001


10-11

Unit 11. Advanced Flow Control

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


11-2

Statement Modifiers
Provide shortcut flow control structures
A simple statement can be followed by a single modifier
Syntax:
statement

control_keyword

test_condition

Control keywords are: if unless while until foreach


Example:

Copyright IBM Corp. 1999, 2001

print "this is it"


if /$pattern/ ;
print
if /$pattern/ ;
print
while <> ;
warn "Starting countdown\n"
if $verbose ;
print
foreach reverse 0..10;
LX222B04T

11-3

Logical Operators For Flow Control


Variations on the conditional statement
Syntax:
expression1 && expression2
expression1 || expression2
expr1

expr2

expr3

Example:
Copyright IBM Corp. 1999, 2001

open FILE, $filename or die "can't open $filename: $!\n" ;


$dir = $_[0] || $ENV{'HOME'} || die "no home dir?\n" ;
$verbose && print "Starting countdown ..." ;
print "$count file", $count == 1 ? '' : 's' ;
LX222B06T

11-4

Loop Modifiers: next


Starts the next iteration of a loop
Syntax:
next
Example:
while (<>) {
/\s*#/ && next ;
/$/ && next ;
++ $cnt ;
} # next lands here

# skip comments
# skip empty lines

Copyright IBM Corp. 1999, 2001

LX222B08T

11-5

Loop Modifiers: redo


Restart the current loop immediately
Syntax:
redo
Example:

Copyright IBM Corp. 1999, 2001

while (<>) { # redo restarts here


next
if /$/ ;
# skip empty lines
redo
if s/\s*#.*// ; # strip comments and redo
++ $line_cnt ;
$char_cnt += length ;
} # next lands here
LX222B10T

11-6

Loop Modifiers: last


last ends the innermost enclosing loop block
Syntax:
last
Example:

Copyright IBM Corp. 1999, 2001

while (<>) { # redo restarts here


chomp ;
last
if /__END__$/ ; # end of data
next
if /$/ ;
# skip empty lines
redo
if s/\s*#.*// ; # strip comments and redo
++ $line_cnt ;
$char_cnt += length ;
} # next lands here
# last lands here
LX222B12T

11-7

Labelling a Statement Block


Provides:
 Documentation of blocks
 A target for next, redo and last
Example:

Copyright IBM Corp. 1999, 2001

LINE: while (<>) {


next LINE if /$/ ;
# skip empty lines
++ $line_cnt ;
WORD: foreach $word (split) {
next WORD
if $word = /\w+$/ ;
next LINE
if $word = /#/ ;
++ $word_cnt ;
}
}
LX222B14T

11-8

Other Uses of Labelled Blocks


A statement block is like a loop body that executes once
Syntax:
{
first_statement ;
second_statement ;
}
It can be used with last and redo:
MENU:
Copyright IBM Corp. 1999, 2001

{
/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

Copyright IBM Corp. 1999, 2001


11-10

Unit 12. Dealing With Files and Directories

Copyright IBM Corp. 1999, 2001

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

Checking File Permissions


Perl provides UNIX shell-like file tests
Syntax:
-X "filename"
-X FILEHANDLE
Where X stands for one of the file test operators
Example:
if (-w

"/etc/passwd") { print "Possibly root"; }

-l MYFILE

&&

print "Is a symlink";

Copyright IBM Corp. 1999, 2001

warn "$_ executable" if -x;

# filename in $_
LX222C04T

12-3

File Accessibility Conditions


The most common tests are:

Copyright IBM Corp. 1999, 2001

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

File Statistics: stat


stat returns a list of information about a file
lstat returns a list of information about a symbolic link
Syntax:
stat(filename)
stat(FILEHANDLE)
lstat(symlink)
Example:

Copyright IBM Corp. 1999, 2001

($dev, $ino, $mode, $nlink, $uid, $gid, $rdev,


$size, $atime, $mtime, $ctime, $blksize,
$blocks) = stat "filename";
($nlink, $size) = (stat "filename")[3,7];
LX222C08T

12-5

The Special Underscore Filehandle


An optimization when using repeated file tests
Syntax:
-X _
stat _
Example:
if ( -d $file and -x _ ) {
print "$file is a dir with execute\n";
}
Copyright IBM Corp. 1999, 2001

LX222C10T

12-6

Creating and Deleting Directories


Syntax:
mkdir(dir_name, permission)
rmdir(dir_name)
Example:
mkdir "datafiles", 0777;
rmdir "datafiles";
mkdir "private", 0700 || die "Can't create dir: $!\n";
LX222C12T

Copyright IBM Corp. 1999, 2001


12-7

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

Using Directory Handles


readdir() returns the next filename or a list of filenames from a
dirhandle
Example:
$dir = "/tmp" ;
opendir(TMP, $dir) or die "can't opendir $dir: $!\n" ;
while ($filename = readdir(TMP)) {
print "$dir/$filename is executable\n"
if -x "$dir/$filename";
}
closedir(TMP);
Copyright IBM Corp. 1999, 2001

opendir(TMP, $dir) or die "can't opendir $dir: $!bsl\n" ;


@readable = grep -r "$dir/$_", readdir TMP;
closedir(TMP);
LX222C18T

12-10

Renaming Files: rename


Syntax:
rename(old_file_name, new_file_name)
Example:
rename("pop", "pop.old");
rename $old, $new;
rename "file", "path/file" or
warn "can't rename file: $!\n";
LX222C20T

Copyright IBM Corp. 1999, 2001


12-11

Dealing With Hard and Soft Links


Perl can create hard and soft (symbolic) links to files
Syntax:
link(file, new_alias)
symlink(file, new_symbolic_link)
readlink(symbolic_link)
Example:

Copyright IBM Corp. 1999, 2001

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

Deleting Files: unlink


Syntax:
unlink(list_of_files)
Example:
unlink @old;

# no error checking!

foreach ( @old ) {
unlink || warn "can't unlink $_: $!\n";
}
Copyright IBM Corp. 1999, 2001

LX222C24T

12-13

Changing Files' Modification Times: utime


Syntax:
utime(last_accessed, last_modified, file_list)
Example:
$latime = $lmtime = time - 120*60 ;
utime($latime, $lmtime, @files);

# 2 hours ago

Copyright IBM Corp. 1999, 2001

$now = time;
foreach $file (@files) {
utime($now, $now, $file) or
warn "can't set time on $file: $!\n";
}
LX222C26T

12-14

Changing Ownership: chown


Syntax:
chown(UID, GID, file_list)
Example:
chown(1001,100, "cat", "dog");
opendir D, $ENV{HOME} or
die "Can't opendir $ENV{HOME}: $!\n";
chown 500, 500, readdir D;
closedir D;
Copyright IBM Corp. 1999, 2001

LX222C28T

12-15

Changing File's Permissions: chmod


Syntax:
chmod(permissions, file1, file2, ...)
Example:
chmod(0666, "/tmp/myfile");
chmod 0755, @mydirs;
LX222C30T

Copyright IBM Corp. 1999, 2001


12-16

Filename Expansion Globbing


Globbing generates a list of filenames using (Linux) shell wildcards
Syntax:
<shell_wildcards>
glob("shell_wildcards")
Example:

Copyright IBM Corp. 1999, 2001

@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

Copyright IBM Corp. 1999, 2001


12-18

Unit 13. Running Perl

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


13-2

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

MacPerl programs can be saved as droplets


LX222D04T

13-3

Command Line Arguments


A Perl program can be run with arguments like any other program
C:\>perl myscript.pl chap1.txt chap2.txt chap3.txt
$ myscript /tmp/*
Within a Perl program the command-line arguments are available in
the @ARGV array
Example:
foreach ( @ARGV ) { print "Next arg is $_\n"; }
while ( $next = shift ) { print $next; }
$source = shift ;
# shift defaults to using @ARGV
Copyright IBM Corp. 1999, 2001

push @ARGV, $def_dir


unless @ARGV;
$target = shift || '.' ;
LX222D06T

13-4

Default Input and @ARGV


The input operator <> with no filehandle
 reads from files in @ARGV, if any
 otherwise reads from STDIN
This emulates how many Linux programs work
This makes it easy to write filters
#!/usr/bin/perl -w
while (<>) {
print
unless /\.\*/;
}

# files from @ARGV or STDIN


# ignore BookMaster comments

Copyright IBM Corp. 1999, 2001

LX222D08T

13-5

Calling Perl Explicitly


Perl can be run explicitly from the command line
This can be useful for one-liners
This is useful when specifying switches
Syntax:
$ perl -switches program program_arguments
Example:

Copyright IBM Corp. 1999, 2001

$ 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

Perl Command Switches


The most common switches for Perl are:

Copyright IBM Corp. 1999, 2001

-h
-v
-w
-n
-p
-a
-e
-c
-T
-d
-i
-l

help text on switches


display version of Perl
enable warning messages
add while(<>) loop around program
add while(<>) loop with trailing print $_
auto-split lines into @F with -n or -p
enter program statements
check syntax (compile) only
taint mode
debug mode
in-place edit files
auto-chomp lines
LX222D12T

13-7

Perl Switches Example


An actual command:
$ ps aux | perl -ane '$F[0] = /nobody$/ && kill 9, $F[1]'
What the code is doing:
LINE:

while(<>) {
@F = split(/\s+/);
$F[0]=/nobody$/ && kill 9, $F[1];

}
LX222D14T

Copyright IBM Corp. 1999, 2001


13-8

Writing Secure Programs


Perl's taint mode tracks insecure data
Enabled with -T switch or when running as Set UID/GID
Perl aborts if tainted data is used in external functions
$tainted = <>;
$a = $tainted;
unlink $a;

# data from a file is tainted


# now $a is also tainted
# fatal error!

Data can be untainted by selecting valid data


$tainted = /(\w+)/;
$a = $1;

# select only word chars.


# now OK, $a is untainted

Also setup environment values: PATH IFS CDPATH ENV BASH_ENV


Copyright IBM Corp. 1999, 2001

$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:

Copyright IBM Corp. 1999, 2001

$ 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

POD Plain Old Documentation


# comments code
Sometimes program documentation is needed
POD is simple markup that embeds documentation in the code
Translators extract documentation and covert to other formats
 HTML, LaTeX, man, text, ...
$ pod2text myprog.pl
C:\> pod2html myprog.pl
Commands must be separated from code by empty lines
Copyright IBM Corp. 1999, 2001

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

End POD processing

=for X Next paragraph only used with formatter X


Copyright IBM Corp. 1999, 2001

=begin X Paragraphs up to =end X only used with formatter X


=end X
LX222D22T

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

Copyright IBM Corp. 1999, 2001


13-13

Unit 14. Report Generation

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


14-2

Understanding Report Formats


Perl started as a language for data manipulation and reporting
It has facilities to generate simple columnar reports with page
headings
Report generation in Perl has three stages
 Declare the report layout(s) with the format statement
 Generate the required information
 Execute the report format with the write statement
LX222E04T

Copyright IBM Corp. 1999, 2001


14-3

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

Copyright IBM Corp. 1999, 2001


14-4

Defining the Report Layout


The actual layout of the output
There are two types of lines:
 picture lines: fixed text and placeholders for variable data
 value lines: a list of variables or expressions corresponding to the
placeholders
Each picture line with placeholders must be followed by a value line
 with a value for each placeholder
Example:
stock#: @######
$stock,

quantity: @##
$quan

Copyright IBM Corp. 1999, 2001

LX222E08T

14-5

A Report Example

Copyright IBM Corp. 1999, 2001

format PICKLIST =
________________________________________
|
|
| stock#: @######
quantity: @##
|
$stock,
$quan
| @<<<<<<<<<<<<<<<<<<<<<<<<<<<
|
$desc
| row:
@##
col: @#
bin: @#
|
$row, $col,
$bin
| price: @####.##
store#: @###
|
$price,
$store
|______________________________________|
.
LX222E10T

14-6

Executing a Report Format


write outputs a format with the current values
Syntax:
write FILEHANDLE
Example:
open(ORDERS ,$ord) or die "cannot open $ord: $!\n";
open(PICKLIST,">$plst") or die "cannot create $plst: $!\n";

Copyright IBM Corp. 1999, 2001

while ( <ORDERS> ) {
chomp;
($stock,$quan,$desc,$row,$col,$bin,$price,$store) =
split (/:/);
write PICKLIST ;
}
LX222E12T

14-7

Changing the Currently Selected Filehandle


The select function can change the default output filehandle
With no filehandle, write uses the default output filehandle
Example:
write PICKLIST;

# use format and filehandle PICKLIST

$old_ofh = select PICKLIST;


while (<>) {
write;
# use format and filehandle PICKLIST
}
select $old_ofh; # restore the previous filehandle
Copyright IBM Corp. 1999, 2001

LX222E14T

14-8

The Page Header Report Format


write outputs a header format when a page is full
Page header formats are named format_TOP
Example:
format PICKLIST_TOP =
@<<<<<<<<<<<<<<<<<<<<<<< Pick List
Page:@<
scalar localtime, $%
---------------------------------------------------.
LX222E16T

Copyright IBM Corp. 1999, 2001


14-9

Report Format Special Variables


Several variables are used when report writing
All apply to the current default output filehandle

Copyright IBM Corp. 1999, 2001

Body format name

$

Header format name

$%

Report page number

$=

Printable lines/page

$-

Number of lines remaining on the page


LX222E18T

14-10

Report Format Variables Example

Copyright IBM Corp. 1999, 2001

# 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

Report Layout Placeholders


There are four classes of placeholders:
Numeric
String
Multiple Line
Expandable
LX222E22T

Copyright IBM Corp. 1999, 2001


14-12

Numeric Variable Placeholders


Right justified with optional decimal point
Syntax:
@######.##
Example:
@######
$stock,

@######.##
$stock * $value

Result:
250

307.50

Copyright IBM Corp. 1999, 2001

LX222E24T

14-13

String Variable Placeholders


Three variations:
@<<<<<<
@>>>>>>
@||||||

left-justified
right-justified
centered

Example:
@<<<<<<<<<< @|||||||||| @>>>
scalar localtime, $title, $%
LX222E26T

Copyright IBM Corp. 1999, 2001


14-14

Multi-line Variable Placeholders


Multi-line strings are normally truncated at the first newline
The multi-line placeholder prints multi-line strings as-is without
truncation
Syntax:
@*
Example:
Description: @*
"This is a \nmulti-line\nparagraph."
Copyright IBM Corp. 1999, 2001

Result:
Description: This is a
multi-line
paragraph.
LX222E28T

14-15

Variable Length Placeholders


Print as much as possible from the variable, removing data once
printed
Example:
Desc: <<<<<<<<<<<<<<<<
$data

<<<<<<<<<<<<<<<<
$data
LX222E30T

Copyright IBM Corp. 1999, 2001


14-16

Summary
 Understanding report formats
 Define a report format
 Executing a report format
 Filehandles in reports
 Format names
 Place holders
LX222E02T

Copyright IBM Corp. 1999, 2001


14-17

Unit 15. Accessing Operating System Data

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


15-2

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

foreach (sort keys %ENV) {


# re-implement printenv
print "$_ = $ENV{$_}\n";
}
LX222F04T

15-3

Perl System Variables


Perl maintains other variables that may be useful
$0

Filename of the current script

$$

This program's Process ID

$?

Status from last child process

$]

Version of Perl interpreter

$O

Name of operating system

$T

Time the script started


LX222F06T

Copyright IBM Corp. 1999, 2001


15-4

Dealing With Binary Data


pack turns a list of values into a binary string
unpack turns a binary string into a list of values
Both functions use a template string to specify the format of the
data
Syntax:
pack(template, list)
unpack(template, expression)
Example:
Copyright IBM Corp. 1999, 2001

@ip = unpack("C4", $binstr);


$binstr = pack "CCCC", @ip; # same as C4
$binstr = pack "C*", 138, 96, 66, 34;
($eng, $dutch) = unpack 'A31 A*', $dict_buf;
LX222F08T

15-5

Manipulating Binary Data


Perl has bitwise operators
&

AND 15 & 2 is 2

OR 16 | 2 is 18

XOR 15  2 is 13

<<

Left shift 15 << 2 is 60

>>

Right shift 15 >> 2 is 3

Also available as assignment operators


&=

|=

=

<<=

>>=

Copyright IBM Corp. 1999, 2001

These operator treat their operands as bit-strings


16
00010000
"A"
01000001

|
2
is
18
| 00000010
00010010
&
"X"
is
"@"
& 01011000
01000000
LX222F10T

15-6

Obtaining Hostname Information


On systems with TCP/IP networking, Perl supports the standard socket
library interface
Example:

Copyright IBM Corp. 1999, 2001

($name, $aliases, $addrtype, $length, @addr) =


gethostbyname('www.training.uk.ibm.com');
foreach (@addr) {
# list of IP addresses for host
$ipadd = join(".", unpack("C4", $_));
print "$name: has IP address $ipadd\n";
}
while (<>) { # a list of IP addresses, 1/line
chomp;
$ip = pack 'C4', split /\./, $_;
print "$_ is ", scalar gethostbyaddr $ip, 2; # 2 is AF_INET
}
LX222F12T

15-7

Accessing Password Info by Name or ID


Syntax:
getpwuid(UID)
getpwnam(login_name)
Example:
($name, $passwd, $uid, $gid, $quota,
$comment, $gcos, $dir, $shell) =
getpwuid(101) || getpwnam("chrisb");
LX222F14T

Copyright IBM Corp. 1999, 2001


15-8

Password File Sequential Access


Syntax:
setpwent - initialize scan of password file
getpwent - return next entry
endpwent - terminate scan of password file
Example:

Copyright IBM Corp. 1999, 2001

setpwent;
print "Username Shell
Home\n";
while (@pw = getpwent) {
printf "%-8s %-10s %s\n", $pw[0], $pw[8], $pw[7];
}
endpwent;
LX222F16T

15-9

Accessing Group Info by Name or ID


Syntax:
getgrgid(GID)
getgrnam(group_name)
Example:
($name, $gpasswd, $gid, $gmembers) =
getgrgid(223) || getgrnam("perl") ;
LX222F18T

Copyright IBM Corp. 1999, 2001


15-10

Group File Sequential Access


Syntax:
setgrent - initialize scan of the group file
getgrent - return the next entry
endgrent - terminate scan of the group file
Example:

Copyright IBM Corp. 1999, 2001

setgrent;
while (@grp = getgrent) {
print $grp[0], "\n" if $grp[3] = /\b$user\b/;
}
endgrent;
LX222F20T

15-11

Time Related Functions


Syntax:
time
gmtime numeric_expression
localtime numeric_expression
Example:
print "Completed in ", time - $T, " seconds.\n";

Copyright IBM Corp. 1999, 2001

($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

Copyright IBM Corp. 1999, 2001


15-13

Unit 16. Running External Programs

Copyright IBM Corp. 1999, 2001

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

Copyright IBM Corp. 1999, 2001


16-2

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

system("who") && print "system 'who' failed\n";


LX222G04T

16-3

Run a Program Without Shell Interaction


Called with a list of parameters, system bypasses the shell
 Even if the arguments contain shell metacharacters
Syntax:
system( list )
Example:
system 'grep * /etc/passwd';
# processed by shell
system 'grep', '*', '/etc/passwd'; # no processing
LX222G06T

Copyright IBM Corp. 1999, 2001


16-4

Run a Program and Capture Output


Backquotes do command substitution the string is replaced by
the output of the command-line
Syntax:
 command-line 
qx/command-line/
Example:
$osl = "The operating system is " . ver ;

Copyright IBM Corp. 1999, 2001

foreach (qx/ls/) {
unlink $_;
}
($heading, @ps) = ps ;
LX222G08T

16-5

Creating Pipes to Other Programs


Filehandles can be pipes to, or from, programs
The position of the pipe symbol | in the filename determines the
mode
Syntax:
open(FILEHANDLE,"command-line |") ;
open(FILEHANDLE,"| command-line") ;

# open for reading


# open for writing

Example:

Copyright IBM Corp. 1999, 2001

open(LS, "ls -al |") || die "starting ls: $!";


open PRINTER, "| lpr" or die "starting lpr: $!";
while (<LS>) { print PRINTER }
close PRINTER or die "closing lpr: $!";
close LS or die "closing ls: $!";
LX222G10T

16-6

Run a Program Overlaying the Current


Program
Syntax:
exec(command-line)
exec(command, argument-list)
If successful, exec() does not return
Example:
exec "cd ; wp $doc"; # passed to shell
die "$0: exec failed: $!\n";
Copyright IBM Corp. 1999, 2001

exec 'ps', @args;


# exec'd directly
die "$0: exec failed: $!\n";
LX222G12T

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

kill signal, list_of_PIDs


Example:
kill 'TERM', $pid or kill 9, $pid;
LX222G14T

16-8

Dealing With Signals


Assign to the %SIG hash to change the default signal effect
Examples:
$SIG{HUP} = 'IGNORE';
$SIG{INT} = 'DEFAULT';

# ignore hangups
# (re)store default (terminate)

$SIG{QUIT} = \&handler; # subroutine to run


sub handler { my $sig = shift; # 1st arg is signal name
die "Received a SIG$sig\n"; }

Copyright IBM Corp. 1999, 2001

$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

Copyright IBM Corp. 1999, 2001


16-10



You might also like