linux, perl - lx222vis

238
Linux and Perl Programming (Course Code LX22) Master Visuals ERC2.1 IBM Learning Services Worldwide Certified Material

Upload: tudorradulescu8914

Post on 24-Dec-2015

8 views

Category:

Documents


4 download

DESCRIPTION

Linux, Perl

TRANSCRIPT

Page 1: Linux, Perl - LX222VIS

���

Linux and Perl Programming(Course Code LX22)

Master VisualsERC2.1

IBM Learning ServicesWorldwide Certified Material

Page 2: Linux, Perl - LX222VIS

Publishing Information

This publication has been produced using BookMaster (Program Number 5668-015),the Document Composition Facility (Program Number 5748-XX9), and Freelance forWindows. 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 theUnited States, or other countries, or both:

Freelance is a trademark of Lotus Development Corporation in the United States, orother countries, or both.

Microsoft, Windows, Windows NT and the Windows 95 logo are trademarks of MicrosoftCorporation in the United States and/or other countries.

UNIX is a registered trademark in the United States and/or other countries licensedexclusively through X/Open Company Limited.

Linux is a registered trademark of Linus Torvalds in the United States, or othercountries, or both.

Other company, product, and service names may be trademarks or service marks ofothers.

AIX BookMaster IBMOS/2

February 2001 Edition

The information contained in this document has not been submitted to any formal IBM test and isdistributed on an “as is” basis without any warranty either express or implied. The use of this informationor the implementation of any of these techniques is a customer responsibility and depends on thecustomer's ability to evaluate and integrate them into the customer's operational environment. While eachitem may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that thesame or similar results will result elsewhere. Customers attempting to adapt these techniques to their ownenvironments 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 ofIBM.Note to U.S. Government Users — Documentation related to restricted rights — Use, duplication ordisclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp.

Page 3: Linux, Perl - LX222VIS

Contents

Course Presentation Material Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

Units

Unit 1. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1Historical Perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2The Usability of Perl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3Availability and Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4Elementary Perl Ideas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5Useful Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7

Unit 2. Simple Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2Scalar Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3Scalar Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4String Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5Additional String Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6Scalar Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8Arithmetic Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9Additional Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10Operator Precedence and Associativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11Operator Precedence and Associativity Examples . . . . . . . . . . . . . . . . . . . . . . . 2-12Scalar Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13Scalar Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14Variable Replacement in Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15Additional Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16The ++ and -- Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-18

Unit 3. I/O Using Standard Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . 3-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2The print Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3The printf Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4The Undefined Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5The Input Operator: <> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6Removing Line Delimiters: chop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7

Copyright IBM Corp. 1999, 2001 iii

Page 4: Linux, Perl - LX222VIS

Removing Line Delimiters: chomp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9

Unit 4. Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2The Statement Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3The if/else Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4The elsif Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5The unless Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6The while Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7The Default Variable: $_ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8while() Shortcut Using $_ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9The until Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10The for Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11The foreach Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13

Unit 5. Lists and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2Defining a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3List Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4The Range Operator: .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5Arrays and Array Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6Array Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7Single Element Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8Multiple Element Access: Array Slices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9Array Operators: push() and pop() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10Array Operators: unshift() and shift() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11Array Operators: splice() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-12List Operators: reverse() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13List Operators: sort() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14Using chop() and chomp() with Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15Array Variable Replacement in Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17

Unit 6. Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2Regular Expression Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3Types of Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4Character Class Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5Character Class Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6Multiple Character Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7A Sequence of Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8Matching Alternatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9

Copyright IBM Corp. 1999, 2001 iv

Page 5: Linux, Perl - LX222VIS

Pattern Multipliers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10Multiplier Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-11Parentheses as Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-12Parentheses as Memory Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13Anchoring Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-14Pattern Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-15The Match Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16The Pattern Binding Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-17The Substitution Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-18Match and Substitution Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-19Substitution Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-20Matching Operator Special Variables 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-21Matching Operator Special Variables 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-22Greedy Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-23Regular Expression Metacharacter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 6-24Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-25

Unit 7. String and Array Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2Generalized Quotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3The here Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4Locating a Substring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5Locating a Substring Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6Substring Extraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7Substring Replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8Alphabetic Case Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9The Translation Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10Translation Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-11The map() Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12The grep() Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-13Breaking a String Apart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14The Quote Words Operator: qw() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-15Joining a List Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16The sort() Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-17Sorting Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-19

Unit 8. Multidimensional and Associative Arrays . . . . . . . . . . . . . . . . . . . . . . 8-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2Defining a Two-Dimensional List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3Two-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4Two-Dimensional Single Element Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-5Going to Three Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6Associative Arrays or Hashes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7

Copyright IBM Corp. 1999, 2001 v

Page 6: Linux, Perl - LX222VIS

Initializing a Hash Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-8Accessing Hash Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9Hash Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-10Hash Operator Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-11Removing Hash Entries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-12Defining a Hash of Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-13Hash of Lists Access Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-14Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-15

Unit 9. User-Defined Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2User-Defined Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3Calling a Subroutine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4Returning from a Subroutine 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5Returning From a Subroutine 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6Private Subroutine Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7Private Subroutine Variables Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8Passing Parameters to a Subroutine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-9A Subroutine Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-10Creating Separate Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-11Using Separate Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-12Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-13

Unit 10. File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2I/O Related Special Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-3Filehandles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4Opening and Closing Filehandles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-5The Default Filehandles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-6Using Other Filehandles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-7Failure to Open an I/O Channel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-8Use Filehandles Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-9The Currently Selected Output Filehandle . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-11

Unit 11. Advanced Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2Statement Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-3Logical Operators For Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-4Loop Modifiers: next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-5Loop Modifiers: redo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-6Loop Modifiers: last . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-7Labelling a Statement Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-8Other Uses of Labelled Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-9

Copyright IBM Corp. 1999, 2001 vi

Page 7: Linux, Perl - LX222VIS

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-10

Unit 12. Dealing With Files and Directories . . . . . . . . . . . . . . . . . . . . . . . . . 12-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2Checking File Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-3File Accessibility Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-4File Statistics: stat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-5The Special Underscore Filehandle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-6Creating and Deleting Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-7Changing Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-8Directory Handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-9Using Directory Handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-10Renaming Files: rename . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-11Dealing With Hard and Soft Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-12Deleting Files: unlink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-13Changing Files' Modification Times: utime . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-14Changing Ownership: chown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-15Changing File's Permissions: chmod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-16Filename Expansion — Globbing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-17Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-18

Unit 13. Running Perl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-2Running Perl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-3Command Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4Default Input and @ARGV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-5Calling Perl Explicitly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-6Perl Command Switches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-7Perl Switches Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-8Writing Secure Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-9Debugging Perl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-10POD — Plain Old Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-11POD Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-12Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-13

Unit 14. Report Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2Understanding Report Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-3Report Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-4Defining the Report Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-5A Report Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-6Executing a Report Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-7Changing the Currently Selected Filehandle . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-8The Page Header Report Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-9

Copyright IBM Corp. 1999, 2001 vii

Page 8: Linux, Perl - LX222VIS

Report Format Special Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-10Report Format Variables Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-11Report Layout Placeholders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-12Numeric Variable Placeholders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-13String Variable Placeholders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-14Multi-line Variable Placeholders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-15Variable Length Placeholders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-16Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-17

Unit 15. Accessing Operating System Data . . . . . . . . . . . . . . . . . . . . . . . . . 15-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-3Perl System Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-4Dealing With Binary Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-5Manipulating Binary Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-6Obtaining Hostname Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-7Accessing Password Info by Name or ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-8Password File Sequential Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-9Accessing Group Info by Name or ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-10Group File Sequential Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-11Time Related Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-12Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-13

Unit 16. Running External Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-1Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2Run a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-3Run a Program Without Shell Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-4Run a Program and Capture Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-5Creating Pipes to Other Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-6Run a Program Overlaying the Current Program . . . . . . . . . . . . . . . . . . . . . . . . 16-7Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-8Dealing With Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-9Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-10

Copyright IBM Corp. 1999, 2001 viii

Page 9: Linux, Perl - LX222VIS

Course Presentation Material Overview

Included in this package are landscape, black and white paper copies of each of thestudent visuals included in the Student Notebook. The paper copies are to be used toreproduce overhead transparencies required to teach the course. It is recommendedthat black-on-clear transparencies be used to reproduce the package.

In addition to the student visuals, a welcome visual SHOULD be included. To ensurethat each student is attending the correct course for which they originally enrolled, thewelcome visual should be used to provide the student with the course name and coursecode upon entering the classroom.

It is advised that upon checking out the classroom prior to the start of class, there betwo overhead projectors in the classroom. This will guarantee that there is a workingoverhead projector available at all times for the duration of the class.

The paper copies and the transparencies created from the paper copies are the propertyof IBM. By way of protecting our intellectual properties, neither the paper copies nor thetransparencies should be given to anyone other than a course certified instructor. Thecopies are not to be used for any purpose other than teaching the course. The securityof this package and the products created as a result of this package are theresponsibility of the course certified instructor.

Copyright IBM Corp. 1999, 2001 ix

Page 10: Linux, Perl - LX222VIS

Unit 1. Overview

Copyright IBM Corp. 1999, 2001 1-1

Page 11: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

1-2

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 thanbeautiful (tiny, elegant, minimal)

Perl is “freeware”

Released for use under the Artistic and/or GNU Public LicenseLX222102T

Page 12: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

1-3

The Usability of Perl

The original aims were:

� Help the UNIX user with common tasks that are too complex ornonportable for the shell

� Assist the UNIX user with tasks that are not worth the effort ofwriting 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

Perl is available on a wide range of platforms: most programswritten in Perl run unchanged on all platforms

LX222104T

Page 13: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

1-4

Availability and Support

The Perl homepage is http://www.perl.com

Perl is free and runs on most UNIX-like systems and many non-UNIXsystems 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

Support was originally available only from newsgroups, mailing-listsand web sites

Commercial support now also availableLX222106T

Page 14: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

1-5

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

; terminates statements

# comments to end of lineLX222108T

Page 15: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

1-6

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 LogicalLX222110T

Page 16: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

1-7

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

Page 17: Linux, Perl - LX222VIS

Unit 2. Simple Data Types

Copyright IBM Corp. 1999, 2001 2-1

Page 18: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-2

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 interpolationLX222200T

Page 19: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-3

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

Perl automatically converts between string and number as requiredLX222204T

Page 20: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-4

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' # exception: \ protects '

'perl\\test' # exception: \ protects \

� Double-quoted strings

"\"Don't go!\" she said." # \ protects "

"low\tbright\tblack\twhite" # \ introduces escapes

"\nThe value is $val.\n" # variable substitution

LX222206T

Page 21: Linux, Perl - LX222VIS

Representationeq

ne

lt

gt

le

ge

Comparison Equal

Not Equal

Less than

Greater than

Less than or equal to

Greater than or equal to

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-5

String Comparison Operators

LX222208T

Page 22: Linux, Perl - LX222VIS

"helloworld"

"goodbye\n"

"out var"

"redredred"

"billbillbill"

"77777"

becomes

becomes

becomes

becomes

becomes

becomes

"hello"."world"

'goodbye'."\n"

"out"." "."var"

"red" x 3

"bill" x (1+2)

(8-1) x 5

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-6

Additional String Operators

Concatenation operator: .

Repetition operator: x

LX222210T

Page 23: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-7

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_632bLX222212T

Page 24: Linux, Perl - LX222VIS

Result5

1

6

1.5

9

1

Example 3 + 2

3 - 2

3 * 2

3 / 2

3 ** 2

3 % 2

Symbol +

-

*

/

**

%

Operation Addition

Subtraction

Multiplication

Division

Exponentiation

Modulus

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-8

Arithmetic Operators

LX222214T

Page 25: Linux, Perl - LX222VIS

Representation==

!=

<

>

<=

>=

Comparison Equal

Not equal

Less than

Greater than

Less than or equal to

Greater than or equal to

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-9

Arithmetic Comparison Operators

LX222216T

Page 26: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-10

Additional Logical Operators

&& and True if all expressions are true

12 > 2 && "A" lt "Z" # true

12 > 2 and "A" gt "Z" # false

|| or True if any expression is true

1 < 2 or 2 < 3 # true (1 < 2)1 > 2 || 2 < 3 # true (2 < 3)

1 > 2 or 2 > 3 # false

! not Negate a logical expression

! ("A" gt "Z") # true

not ("A" lt "Z") # false

The symbol and word version differ only in precedenceLX222218T

Page 27: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-11

Operator Precedence and Associativity

Precedence determines the order of evaluation of operators

� Operators with higher precedence are evaluated before those withlower

1 + 2 * 3 is 1 + (2 * 3) # 7 (not 9)

1 / 2 + 3 is (1 / 2) + 3 # 3.5 (not 1/5)

Associativity determines the order of evaluation of operators with thesame precedence.

� Operators with left associativity evaluate left to right� Operators with right associativity evaluate right to left

3 + 1 - 2 is (3 + 1) - 2 # left associative

3 ** 1 ** 2 is 3 ** (1 ** 2) # right associative

LX222220T

Page 28: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-12

Operator Precedence and AssociativityExamples

Example:

1 + 5 * 6;

56 / 14 / 2;

3 ** 4 ** 5;

"y" . "n" x 3;

9 + 2 x 3;

Use parentheses for clarity!LX222222T

Page 29: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-13

Scalar Variables

A scalar variable stores a single value

The variable name must start with a letter or underscore and cancontain 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 fromfollowing text

Example:

$A $a $a_very_long_name ${var1} $_myvarLX222224T

Page 30: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-14

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 otherexpressions

Assignment is an operator that returns the value assigned

Examples:

$a = 17 + 22;

${b} = $c;

$d = "hello";

${e} = 22 x 3;

$x = $y = $z = 0;LX222226T

Page 31: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-15

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:

$a="hello there $b"

$var = "Mon";

$varday = "wrong";

$out = "Today is $varday"; # Today is wrong

$out = "Today is ${var}day"; # Today is Monday

$out2 = "Today is $var"."day"; # Today is Monday

$out3 = "Today is " . $var . "day"; # Today is Monday

$var = "Tues";LX222228T

Page 32: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-16

Additional Assignment Operators

Binary, String and Numeric Operators can be combined withassignment

Example:

$g += 11; # same as $g = $g + 11;

$e *= 3; # same as $e = $e * 3;

$str .= "a"; # same as $str = $str . "a";

You can also use:

-= /= %= **= x= &&= ||=LX222230T

Page 33: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-17

The ++ and -- Operators

Autoincrement and autodecrement operators

Syntax:

++$a; # increment before use

$a++; # increment after use

--$a; # decrement before use

$a--; # decrement after use

Example:

$x = 11;

print ++$x; # prints 12, $x is 12

print $x++; # prints 12, $x is 13

print --$x; # prints 12, $x is 12

print $x--; # prints 12, $x is 11LX222232T

Page 34: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

2-18

Summary

� Basic scalar data

� Scalar variables

� Assignment operators

� Arithmetic operators

� String operators

� Operator precedence and associativity

� Variable interpolationLX222202T

Page 35: Linux, Perl - LX222VIS

Unit 3. I/O Using Standard Input and Output

Copyright IBM Corp. 1999, 2001 3-1

Page 36: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

3-2

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 delimitersLX222300T

Page 37: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

3-3

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;LX222304T

Page 38: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

3-4

The printf Operator

Provides formatted output

The first argument is a string specifying the number and format ofthe 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;LX222306T

Page 39: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

3-5

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 ofuninitialized variables

#!/usr/bin/perl -w

print 2 * $x; # output: 0 and the warning message:-

# Use of uninitialized value at - line 1.LX222308T

Page 40: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

3-6

The Input Operator: <>

The <> operator reads data from a filehandle

Syntax:

<FILEHANDLE>

Example:

print "Enter elevation: ";

$a = <STDIN> ;

$line = <> ;

If no filehandle is specified, <>:

� reads from files on the command line

� or STDIN if no files are specifiedLX222310T

Page 41: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

3-7

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;

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

Page 42: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

3-8

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:

chomp $x;

chomp( $x = <STDIN>);

$count = chomp( $x = <STDIN> );LX222314T

Page 43: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

3-9

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 delimitersLX222302T

Page 44: Linux, Perl - LX222VIS

Unit 4. Flow Control

Copyright IBM Corp. 1999, 2001 4-1

Page 45: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-2

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 statementLX222400T

Page 46: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-3

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 ;

}LX222404T

Page 47: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-4

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:

if ( $month < 13 ) {print "A possible month of the year" ;

}

else {

print "Invalid month ($month) > 12\n";

}LX222406T

Page 48: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-5

The elsif Construct

Provides for multiple test conditions

Syntax:

if (test_expression1) {statements_1}

elsif (test_expression2) {statements_2}

else {statements_3}

Example:

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" ;

}LX222408T

Page 49: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-6

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

Page 50: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-7

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 ++ ;

}

do {

print $x -- ;

sleep 1;

} while ( $x >= 0 );LX222412T

Page 51: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-8

The Default Variable: $_

A special global variable

Used by many functions if no other variable specified:

print; # print $_;

chop; # chop $_;

chomp; # chomp $_;LX222414T

Page 52: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-9

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:

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

print $_;

}LX222416T

Page 53: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-10

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

}LX222418T

Page 54: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-11

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;

}LX222420T

Page 55: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-12

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;

}

If omitted, the loop variable defaults to $_

foreach ("red", "white", "blue") {

print;

}LX222422T

Page 56: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

4-13

Summary

� Statement blocks

� if/else statement

� elsif branch

� the unless variation

� while and until statements

� for statement

� foreach statementLX222402T

Page 57: Linux, Perl - LX222VIS

Unit 5. Lists and Arrays

Copyright IBM Corp. 1999, 2001 5-1

Page 58: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-2

Objectives

After completing this unit, you should be able to use:

� Lists

� Arrays

� Array variables

� Array operatorsLX222500T

Page 59: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-3

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 operatorsLX222504T

Page 60: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-4

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:

()

List Assignment:

($l, $m, $n) = (1, 2, 3);

($l, $m) = ($m, $l);LX222508T

Page 61: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-5

The Range Operator: ..

Creates a list of all values between its operands

Syntax:

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

("A" .. "E") # ("A","B","C","D","E")

Example:

foreach (1 .. 1_000) { ... }

print "A" .. "Z", "\n";LX222506T

Page 62: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-6

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 0LX222510T

Page 63: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-7

Array Assignment

Simple Assignment:

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

@my_nums = @numbers; # a copy of @numbers

@one_num = (1); # list with one member

@more_nums = (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: 4LX222512T

Page 64: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-8

Single Element Access

Individual elements are accessed with a $ prefix and a subscript (orindex) in brackets

Syntax:

$arrayname[ index ]

Example:

@nums = (2,4,6);

$p = $nums[0]; # 2

$nums[0] = 5; # (5,4,6)

$q = $nums[$p]; # 6

$r = $nums[$p-1]; # 4

$nums[2] += 5; # (5,4,11)

$nums[4] += 1; # (5,4,11,undef,1)

$nums[-1] += 5; # (5,4,11,undef,6)LX222514T

Page 65: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-9

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]; # (9, 8, 7, 6)

@nums[1, 3] = (2, 2) ; # (5, 2, 7, 2, 9)

@nums[2, 4] = (4, 3) ; # (5, 2, 4, 2, 3)LX222516T

Page 66: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-10

Array Operators: push() and pop()

Add or remove elements at the end of an array

Syntax:

push(@arrayname, list, of, values)

pop(@arrayname)

Example:

@old = (5,21,38,16) ;

push(@old,99,77) ; # (5,21,38,16,99,77)

$new = 88 ;

push(@old,$new) ; # (5,21,38,16,99,77,88)

$last = pop(@old) ; # 88 (5,21,38,16,99,77)

$last = pop(@old) ; # 77 (5,21,38,16,99)LX222518T

Page 67: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-11

Array Operators: unshift() and shift()

Add or remove elements at the start of an array

Syntax:

unshift(@arrayname, list, of, values)

shift(@arrayname)

Example:

@old = (5,21,38,16) ;

$new = 66 ;

unshift(@old, $new) ; # (66,5,21,38,16)

shift(@old) ; # (5,21,38,16)

$next = shift(@old) ; # 5 (21,38,16)

while ( $next = shift(@old) ) { ... }LX222520T

Page 68: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-12

Array Operators: splice()

Add or remove elements anywhere in an array

Syntax:

splice(@arrayname, offset, remove, list, of, values)

Example:

@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

Page 69: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-13

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); # (40,30,20,10)

@countdown = reverse 0..10;LX222524T

Page 70: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-14

List Operators: sort()

Returns a copy of its argument list in ascending character setsequence

Syntax:

sort(@array)

sort(list)

Example:

@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

Page 71: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-15

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:

@output = ("hello\n","world\n");

$count = chomp (@output); # @output is ("hello","world")

@output = ("hello\n","world\n");

chop (@output); # @output is ("hello","world")LX222528T

Page 72: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-16

Array Variable Replacement in Strings

Double-quoted strings are scanned for array variables

When found, a variable is replaced with its current value

Example:

@pat = (1,"z",2,"y",3,"x");

$p = 3;

print "This output is $pat[1]" ; # z

print "This output is $pat[$p-1]" ; # 2

print "This output is @pat" ; # 1 z 2 y 3 x

print "This output is ", @pat; # 1z2y3x

print "This output is @pat[2,3]" ; # 2 y

print "This output is @pat[$p*2-1]" ; # x

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

Page 73: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

5-17

Summary

� Lists

� Arrays

� Array variables

� Array operatorsLX222502T

Page 74: Linux, Perl - LX222VIS

Unit 6. Regular Expressions

Copyright IBM Corp. 1999, 2001 6-1

Page 75: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-2

Objectives

After completing this unit, you should understand the concepts ofregular expressions and be able to use:

� Single-character patterns

� Grouping patterns

� Anchoring patterns

� Pattern precedence

� The matching and substitution operatorsLX222600T

Page 76: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-3

Regular Expression Concepts

Regular Expressions are used to describe a string of characters

Perl's match operator uses regular expressions to search formatching text

The substitute operator uses regular expressions to select the textto be replaced

A regular expression is made up of patterns of ordinary charactersand special metacharacters

Regular expressions are usually shown in slashes: /patterns/

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

LX222604T

Page 77: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-4

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

To match metacharacters for example . [ ]

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

Page 78: Linux, Perl - LX222VIS

an uppercase English vowel

a single, non-zero, even digit

define range using hyphen

hyphen first or last to match a hyphen

lowercase alphabetic

initial caret specifies a negated character class

NOT a lower case alphabetic English letter

an alphanumeric - multiple ranges are OK

/[AEIOU]/

/[2468]/

/[0-5]/

/[789-]/

/[a-z]/

/[�0-9]/

/[�a-z]/

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

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-5

Character Class Examples

LX222608T

Page 79: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-6

Character Class Shortcuts

Perl provides a set of shortcuts for character classes

Syntax:

\d digits: [0-9]

\D non-digits: [�0-9]\w word characters: [A-Za-z0-9_]

\W non-word characters: [�A-Za-z0-9_]\s whitespace: [ \t\n\r\f]

\S non-whitespace: [� \t\n\r\f]

Shortcuts are “locale aware” if locales are available and configured

Example:

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

Page 80: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-7

Multiple Character Patterns

We usually need to match more than one character

There are four ways of grouping patterns to match multiplecharacters

� Sequence

� Alternation

� Multipliers

� Parentheses as memory and for precedence

We will look at each in turnLX222612T

Page 81: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-8

A Sequence of Patterns

A sequence of patterns, matches the sequence of charactersmatched 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"; }

Match 2.4.any-single-digitLX222614T

Page 82: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-9

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"; }LX222616T

Page 83: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-10

Pattern Multipliers

A multiplier is a special character applied to the immediatelypreceding pattern

A pattern and its multiplier can match variable numbers ofcharacters

Syntax:

? zero or one

* zero or more

+ one or more

{m,n} from m to n occurrences

{m,} m or more

{,n} at most n

{i} exactly i occurrencesLX222618T

Page 84: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-11

Multiplier Examples

/ca?t/ # ct cat

/ye*s/ # ys yes yees yeees . . .

/wh+y/ # why whhy whhhy whhhhy . . .

/wh{5}o/ # whhhhho

/ca{3,}r/ # caaar caaaar caaaaar . . .

/co{1,4}w/ # cow coow cooow coooow

/A*/ # “” yes why who car cow A AA AAA . . .LX222620T

Page 85: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-12

Parentheses as Memory

� Parentheses store the matched text in special registers for reuselater 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:

/(.)(.).\2\1/

/(\w+)\s+\1/LX222622T

Page 86: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-13

Parentheses as Memory Example

Regular Expression is

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

DxEkyFkyGxH match \1 is x, \2 is ky

D6Ek9Fk9G6H match \1 is 6, \2 is k9

DxEkyFkyG1H no

DxEkyFkGxH no

DxEkyFwG8H noLX222624T

Page 87: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-14

Anchoring Patterns

Anchor patterns match positions not characters in the searchedstring

Syntax:

/�pattern/ match pattern at start of string

/pattern$/ match pattern at end of string

Example:

/\bpattern/ match pattern at a boundary

/\bpattern\b/ match the word pattern

/\Bpattern/ match pattern when not a boundary

/Jim\B/ match Jimmy and Jims but not "Jim James"LX222626T

Page 88: Linux, Perl - LX222VIS

Symbols()? * + {m,n}ABC � $ \b \B|

Name Parentheses Multipliers Sequence/Anchoring Alternation

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-15

Pattern Precedence

Patterns have precedence just like operators

The table lists patterns in descending order of precedence

Example:

xy*z matches xz, xyz, xyyz, xyyyz, xyyyyz, etc.

(xyz)* matches "", xyz, xyzxyz, xyzxyzxyz, etc.

t|v$ matches t anywhere OR v at end of string

(t|v)$ matches EITHER t OR v at end of stringLX222628T

Page 89: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-16

The Match Operator

Returns true or false depending on whether its regular expressionmatches a string

The default match target is $_

Syntax:

/regular_expression/

m#regular_expression#

m{regular_expression}

Example:

m/�From: / ;/�From: / ;m#/.*/(.*)# ;

m{�From: (.*)} ;LX222630T

Page 90: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-17

The Pattern Binding Operators

Specifies the target of a match operation

Syntax:

$variable =˜ /reg_expr/

$variable !˜ /reg_expr/

Example:

if ( $answer =˜ /�[Yy]/ ) { ... }

$name =˜ /(\w+)\s+((\w\.?)\s+)?(\w+)/;

while ( $answer !˜ /�[YyNn]/ ) {print "Enter 'Y'es or 'N'o: ";

chomp($answer = <STDIN>);

}LX222632T

Page 91: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-18

The Substitution Operator

Replaces a string matched with a regular expression

The default target is $_

The traditional delimiters are /// — any other single character or twopairs of brackets can be used

Syntax:

s/pattern/replacement_string/

Example:

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 replacementLX222634T

Page 92: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-19

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; } }

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 lineLX222636T

Page 93: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-20

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

Page 94: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-21

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

print $�; # "this is a "

print $&; # "simple"

print $'; # " sentence"LX222640T

Page 95: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-22

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 theregular expression with the same content

Example:

$line =˜ m/�From: (.*)/ ;$sender = $1 ;

Parenthesized patterns are also returned by matching if thedestination expects a list

$string = "this is a simple sentence" ;

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

Page 96: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-23

Greedy Matching

Regular expressions match the longest possible string from a givenstart position

Example:

$_ = "this is a simple sentence" ;

/(t.*s)/ ; # $1 is 'this is a simple s'

Multipliers can be made “un-greedy” by appending ?

/(t.*?s)/ ; # $1 is 'this'

m#<b>(.*?)</b>#sig ; # only bold phrasesLX222644T

Page 97: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-24

Regular Expression Metacharacter Summary

Metacharacters are symbols that have special meaning in a regularexpression

[ ] . \ � | $ ? * + { } ()

The regular expression delimiters are also special

Protect all these characters with \ to match themselves literallyLX222646T

Page 98: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

6-25

Summary

� Concepts of Regular Expressions

� Single-character patterns

� Grouping patterns

� Anchoring patterns

� Pattern precedence

� The matching and substitution operatorsLX222602T

Page 99: Linux, Perl - LX222VIS

Unit 7. String and Array Processing

Copyright IBM Corp. 1999, 2001 7-1

Page 100: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-2

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:

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

LX222700T

Page 101: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-3

Generalized Quotes

Operators that provide alternative string delimiters

Syntax:

q/single quoted string/

qq{double quoted string}

Example:

$string = 'This isn\'t Bob\'s car!';

$string = q/This isn't Bob's car!/;

$string = 'C:\\windows\\system\\viewers\\file';

$string = q/c:\windows\system\viewers\file/;

$string = "\"Help!\" $name cried.";

$string = qq("Help!" $name cried.);LX222704T

Page 102: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-4

The here Document

Another way of quoting text — especially useful for large strings

Syntax:

<<DELIMITERstring

DELIMITER

Example:

print <<EOS1, <<'EOS2' ;$date

Dear $name,

EOS1

Single quoted string: no $variable interpolation

EOS2LX222706T

Page 103: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-5

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)

Example:

if ( ($pos = index($t, '../') >= 0) { ... }LX222708T

Page 104: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-6

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"); # -1LX222710T

Page 105: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-7

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)

$line = <>;

$delim = substr($line, -1); # \n (on Linux!)LX222712T

Page 106: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-8

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"LX222714T

Page 107: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-9

Alphabetic Case Operators

Return a copy of the source string with (possibly) altered case

Syntax:

lc( string )

lcfirst( string )

uc( string )

ucfirst( string )

Example:

print lc $code ;

$key = uc $key ;

print ucfirst lc $name ;

print uc ; # use $_

The default source is $_LX222716T

Page 108: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-10

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:

$_ = 'hello cruel world' ;

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

Page 109: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-11

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/; # Uryyb Jbeyq!

tr/A-Za-z/N-ZA-Mn-za-m/; # Hello World!LX222720T

Page 110: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-12

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:

@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

Page 111: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-13

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 theoutput list

Syntax:

grep expression, list

grep {block} list

Example:

@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

Page 112: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-14

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) ;

$_ = "root 391 1 0 Mar14 ? 00:00:00 lpd";

($user, $pid, undef) = split;

($user, $pid, undef) = split /\s+/, $_, 3;LX222726T

Page 113: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-15

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:

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

seven eight nine/;LX222728T

Page 114: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-16

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) ;

print join("\n", @INC), "\n"; # needs a trailing \n

print join "\n", @INC, ''; # append a dummy (null) value

$domain = 'training.uk.ibm.com' ;

print join '.', reverse split /\./, $domain ;

LX222730T

Page 115: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-17

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 greaterthan zero

� depending on the comparison of two values

Syntax:

sort list

sort { statements } list

sort subroutine list

The comparison operators are typically used:

<=> numeric comparison (spaceship) operator

cmp alphanumeric comparisonLX222732T

Page 116: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-18

Sorting Examples

@names = qw( one two three four five six );

@sorted = sort (@names); # five four one six three two

@sorted = sort { $a cmp $b } (@names);

@reversed = sort { $b cmp $a } @names;

# two three six one four five

@numbers = (3,11,5,23,13,7,19,29,17,1) ;

sub lotohi { $a <=> $b }

sub hitolo { $b <=> $a }

@l2h = sort lotohi @numbers;

#1,3,5,7,11,13,17,19,23,29

@h2l = sort hitolo @numbers;

# 29,23,19,17,13,11,7,5,3,1LX222734T

Page 117: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

7-19

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

LX222702T

Page 118: Linux, Perl - LX222VIS

Unit 8. Multidimensional and Associative Arrays

Copyright IBM Corp. 1999, 2001 8-1

Page 119: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-2

Objectives

After completing this unit, you should be able to use:

� Multidimensional arrays

� Associative arrays or hashes

� Hash operatorsLX222800T

Page 120: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-3

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 isanother list enclosed in brackets

Example:

( ['Fred', 'M', 'B', 'systems analyst'] ,

['Wilma', 'F', 'A', 'programmer'] ,

['Betty', 'F', 'M', 'network analyst'] ,

['Barney', 'M', 'P', 'systems engineer'] )LX222804T

Page 121: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-4

Two-Dimensional Arrays

Assignment:

@students = (

['Fred', 'M', 'B', 'systems analyst'] ,

['Wilma', 'F', 'A', 'programmer'] ,

['Betty', 'F', 'M', 'network analyst'] ,

['Barney', 'M', 'P', 'systems engineer']

) ;

Adding and removing elements:

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

@newone = ('Bam Bam', 'M', 'B', 'senior programmer');

push(@students, [ @newone ] );

@fred = @{ shift @students };LX222806T

Page 122: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-5

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] ; # BarneyLX222808T

Page 123: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-6

Going to Three Dimensions

Assignment:

@students = (

['Fred', 'M', ['B','C','A'], 'systems analyst'] ,

['Wilma', 'F', ['A','F','D'], 'programmer'] ,

['Betty', 'F', ['M','G','A'], 'network analyst'] ,

['Barney', 'M', ['P','E'], 'systems engineer']

) ;

Element access:

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

Page 124: Linux, Perl - LX222VIS

valuesystems analyst

programmer

network analyst

systems engineer

key Fred

Wilma

Betty

Barney

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-7

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

LX222812T

Page 125: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-8

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 => 'systems analyst' ,

Wilma => 'programmer' ,

Betty => 'network analyst' ,

Barney => 'systems engineer'

) ;

From other hashes:

%workers = %students;LX222814T

Page 126: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-9

Accessing Hash Elements

Syntax:

$hashname{ key }

Adding and changing hash values:

$students{ 'Wilma' } = 'Operator';

$students{ 'Pebbles' } = 'Trainee';

$students{ 'Wilma' } = 'Supervisor';

Printing hash values:

print $students{ 'Barney' };LX222816T

Page 127: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-10

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)

LX222818T

Page 128: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-11

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 "

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

Page 129: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-12

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

exists tests whether a hash contains the key

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

Page 130: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-13

Defining a Hash of Lists

A hash can have a list as its value

Example:

%students = (

Fred => ['M', 'B', 'systems analyst'] ,

Wilma => ['F', 'A', 'operator'] ,

Betty => ['F', 'P', 'network analyst'] ,

Barney => ['M', 'P', 'systems engineer']

) ;LX222824T

Page 131: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-14

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:

%students = (Wilma => { gender => 'F',education => 'A', job => 'operator'},

...);

print $students{'Wilma'}{'job'};LX222826T

Page 132: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

8-15

Summary

� Multidimensional arrays

� Associative arrays or hashes

� Hash operatorsLX222802T

Page 133: Linux, Perl - LX222VIS

Unit 9. User-Defined Subroutines

Copyright IBM Corp. 1999, 2001 9-1

Page 134: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-2

Objectives

After completing this unit, you should be able to:

� Define subroutines

� Use user-defined subroutines

� Return from subroutines

� Pass variables to subroutines

� Use packagesLX222900T

Page 135: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-3

User-Defined Subroutines

A subroutine or function is a named statement block

The name must be unique within the program

The name must start with an alphabetic or underscore

Syntax:

sub subname {statements}

Example:

sub print_line {

print '-' x 80, "\n";

}LX222904T

Page 136: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-4

Calling a Subroutine

Syntax:

&subname

subname()

subname

Example:

&print_line; # original (Perl4) format

print_line(); # & optional in Perl5 with parentheses

print_line; # () optional in Perl5 if sub predefinedLX222906T

Page 137: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-5

Returning from a Subroutine 1

The return statement exits a subroutine immediately

With an optional return value

Syntax:

return (expression)

Example:

sub myadd {

$debug && print "\$a=$a, \$b=$b\n";

return $a + $b;

}

$a = 1;

$b = 4;

print 3 * myadd(); # 15

$c = myadd();LX222908T

Page 138: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-6

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) { $a; }

else { $b; }

}

sub mypow { $a ** $b; }LX222910T

Page 139: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-7

Private Subroutine Variables

Private variables can be created in a user subroutine with the myand local operators

Syntax:

my ( $var )

local ( $var1, @array, %hash )

Example:

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 lineLX222912T

Page 140: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-8

Private Subroutine Variables Example

print $m, $l; # undef, undef

mysub1();

print $m, $l; # 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'

}

sub mysub2 {

print $m, $l; # undef, 'local-mysub1'

}LX222914T

Page 141: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-9

Passing Parameters to a Subroutine

Parameters are passed to subroutines as a list

Example:

mymax( @scores );

Subroutines receive their parameters in the special array @_

sub mymax {

my $max = shift; # defaults to @_ in subroutines

foreach ( @_ ) {

$_ > $max && $max = $_ ;

}

$max; # return value

}LX222916T

Page 142: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-10

A Subroutine Example

#!/usr/bin/perl -w

my ($min, $max, $ave) = minmaxave( 2, 22, -3, 14, 6, 10);

# -3, 22, 8.5

sub minmaxave {

my($min, $max, $sum, $cnt) = (0,0,0,0);

foreach ( @_ ) {

if ($_ < $min) { $min = $_ }

if ($_ > $max) { $max = $_ }

$sum += $_;

++ $cnt;

}

$min, $max, $sum / $cnt;

}LX222918T

Page 143: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-11

Creating Separate Namespaces

A package statement declares a separate namespace

The declaration has the same scope as my()

Example:

package utils;

sub min {

$min = shift;

foreach (@_) { if ($_ < $min) { $min = $_ } }

$min;

}

sub max {

$max = shift;

foreach (@_) { if ($_ > $max) { $max = $_ } }

$max;

}LX222920T

Page 144: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-12

Using Separate Namespaces

Prefix a symbol name with the package to refer to names in othernamespaces

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

Page 145: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

9-13

Summary

� Define subroutines

� Use user-defined subroutines

� Return from subroutines

� Pass variables to subroutines

� Use packagesLX222902T

Page 146: Linux, Perl - LX222VIS

Unit 10. File I/O

Copyright IBM Corp. 1999, 2001 10-1

Page 147: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

10-2

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 filehandleLX222A00T

Page 148: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

10-3

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:

$| = 1;

foreach ( reverse 0 .. 10 ) { print "$_ "; sleep 1; }

{ local $, = "\n"; local $\ = "\n";

print @names; # one field/line and trailing newline

}LX222A04T

Page 149: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

10-4

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 UPPERCASELX222A06T

Page 150: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

10-5

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:

open(INFILE, $filename) ;

open PASSWD, "<$passwd" ;

unless ( open OUTFILE, ">$outfile" ) { ... }

if ( open(LOGFILE, ">> $logfile") { ... }

close(LOGFILE);

close PASSWD;LX222A08T

Page 151: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

10-6

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 commandprompt

� avoiding the need for opening files in the program

$ myprog <data.in >data.out 2>>error.logLX222A10T

Page 152: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

10-7

Using Other Filehandles

Syntax:

print(FILEHANDLE list)

printf(FILEHANDLE "format", list)

<FILEHANDLE>

Example:

print(STDERR "Starting ...");

print LOGFILE "starting at ", scalar localtime, "\n" ;

while ( <INFILE> ) { ... }LX222A12T

Page 153: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

10-8

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:

unless (open MYFILE, ">$myfile) {die "Sorry, cannot create $myfile: $!\n" ;

}

open(MYFILE,">$myfile") ||

die "Sorry, cannot create $myfile: $!\n" ;LX222A14T

Page 154: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

10-9

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($_);

}

close(REPORT);

close(INVENTORY);LX222A16T

Page 155: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

10-10

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

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

print $v; # to REPORT

select $csf; # restore the previous valueLX222A18T

Page 156: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

10-11

Summary

� Use more print operations

� Open and close filehandles

� Read and write user-defined filehandles

� Select the default output filehandleLX222A02T

Page 157: Linux, Perl - LX222VIS

Unit 11. Advanced Flow Control

Copyright IBM Corp. 1999, 2001 11-1

Page 158: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

11-2

Objectives

After completing this unit, you should be able to use:

� More flow control structures

� The loop modifiers: last, next and redo

� Block labelsLX222B00T

Page 159: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

11-3

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:

print "this is it" if /$pattern/ ;

print if /$pattern/ ;

print while <> ;

warn "Starting countdown\n" if $verbose ;

print foreach reverse 0..10;LX222B04T

Page 160: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

11-4

Logical Operators For Flow Control

Variations on the conditional statement

Syntax:

expression1 && expression2

expression1 || expression2

expr1 ? expr2 : expr3

Example:

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

Page 161: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

11-5

Loop Modifiers: next

Starts the next iteration of a loop

Syntax:

next

Example:

while (<>) {/�\s*#/ && next ; # skip comments

/�$/ && next ; # skip empty lines

++ $cnt ;

} # next lands hereLX222B08T

Page 162: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

11-6

Loop Modifiers: redo

Restart the current loop immediately

Syntax:

redo

Example:

while (<>) { # redo restarts herenext if /�$/ ; # skip empty lines

redo if s/\s*#.*// ; # strip comments and redo

++ $line_cnt ;

$char_cnt += length ;

} # next lands hereLX222B10T

Page 163: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

11-7

Loop Modifiers: last

last ends the innermost enclosing loop block

Syntax:

last

Example:

while (<>) { # redo restarts here chomp ;

last if /�__END__$/ ; # end of datanext if /�$/ ; # skip empty lines

redo if s/\s*#.*// ; # strip comments and redo

++ $line_cnt ;

$char_cnt += length ;

} # next lands here

# last lands hereLX222B12T

Page 164: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

11-8

Labelling a Statement Block

Provides:

� Documentation of blocks

� A target for next, redo and last

Example:

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

Page 165: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

11-9

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

/who/ and $opt = 1 and last MENU;

/what/ and $opt = 2 and last MENU;

/when/ and $opt = 3 and last MENU;

$opt = 99;

}LX222B16T

Page 166: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

11-10

Summary

� More flow control structures

� The loop modifiers: last, next and redo

� Block labelsLX222B02T

Page 167: Linux, Perl - LX222VIS

Unit 12. Dealing With Files and Directories

Copyright IBM Corp. 1999, 2001 12-1

Page 168: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-2

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 globbingLX222C00T

Page 169: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-3

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";

warn "$_ executable" if -x; # filename in $_LX222C04T

Page 170: Linux, Perl - LX222VIS

Conditionfile/directory readablefile/directory writablefile/directory executablefile/directory owned by userfile/directory existsfile exists and is a filedirectory existsfile exists and is a symbolic linkfile exists and has zero sizefile exists and has non-zero size

Test -r -w -x -o -e -f -d -l -z -s

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-4

File Accessibility Conditions

The most common tests are:

LX222C06T

Page 171: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-5

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:

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

$size, $atime, $mtime, $ctime, $blksize,

$blocks) = stat "filename";

($nlink, $size) = (stat "filename")[3,7];LX222C08T

Page 172: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-6

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";

}LX222C10T

Page 173: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-7

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

Page 174: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-8

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; # $HOMELX222C14T

Page 175: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-9

Directory Handles

A Directory Handle can be used to get the names of all the files in adirectory

Directory Handles are always opened read-only: they can only beused to read filenames

A Directory Handle must be opened before use and should be closedafterwards to conserve resources

Syntax:

opendir(DIR_HANDLE, directory_name)

closedir(DIR_HANDLE)

Example:

$dir = "/etc" ;

opendir(DIR,$dir) || die "can't opendir $dir: $!\n";

closedir DIR;LX222C16T

Page 176: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-10

Using Directory Handles

readdir() returns the next filename or a list of filenames from adirhandle

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);

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

@readable = grep -r "$dir/$_", readdir TMP;

closedir(TMP);LX222C18T

Page 177: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-11

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

Page 178: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-12

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:

link($today, 'current');

symlink($path, '/tmp/test') or

warn "can't symlink $path: $!\n";

print "$path -> ", readlink($path), "\n"

if -l $path ;LX222C22T

Page 179: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-13

Deleting Files: unlink

Syntax:

unlink(list_of_files)

Example:

unlink @old; # no error checking!

foreach ( @old ) {

unlink || warn "can't unlink $_: $!\n";

}LX222C24T

Page 180: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-14

Changing Files' Modification Times: utime

Syntax:

utime(last_accessed, last_modified, file_list)

Example:

$latime = $lmtime = time - 120*60 ; # 2 hours ago

utime($latime, $lmtime, @files);

$now = time;

foreach $file (@files) {

utime($now, $now, $file) or

warn "can't set time on $file: $!\n";

}LX222C26T

Page 181: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-15

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;LX222C28T

Page 182: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-16

Changing File's Permissions: chmod

Syntax:

chmod(permissions, file1, file2, ...)

Example:

chmod(0666, "/tmp/myfile");

chmod 0755, @mydirs;LX222C30T

Page 183: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-17

Filename Expansion — Globbing

Globbing generates a list of filenames using (Linux) shell wildcards

Syntax:

<shell_wildcards>glob("shell_wildcards")

Example:

@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

Page 184: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

12-18

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 globbingLX222C02T

Page 185: Linux, Perl - LX222VIS

Unit 13. Running Perl

Copyright IBM Corp. 1999, 2001 13-1

Page 186: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-2

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 documentationLX222D00T

Page 187: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-3

Running Perl

Perl scripts can always be run by running Perl with the script as anargument

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

MacPerl programs can be saved as “droplets”LX222D04T

Page 188: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-4

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 inthe @ARGV array

Example:

foreach ( @ARGV ) { print "Next arg is $_\n"; }

while ( $next = shift ) { print $next; }

$source = shift ; # shift defaults to using @ARGV

push @ARGV, $def_dir unless @ARGV;

$target = shift || '.' ;LX222D06T

Page 189: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-5

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 (<>) { # files from @ARGV or STDIN

print unless /�\.\*/; # ignore BookMaster comments

}LX222D08T

Page 190: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-6

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:

$ 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' *.awLX222D10T

Page 191: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-7

Perl Command Switches

The most common switches for Perl are:

-h help text on switches-v display version of Perl-w enable warning messages-n add while(<>) loop around program-p add while(<>) loop with trailing print $_-a auto-split lines into @F with -n or -p-e enter program statements-c check syntax (compile) only-T taint mode-d debug mode-i in-place edit files-l auto-chomp lines

LX222D12T

Page 192: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-8

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

Page 193: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-9

Writing Secure Programs

Perl's “taint mode” tracks insecure dataEnabled with -T switch or when running as Set UID/GIDPerl aborts if “tainted” data is used in external functions

$tainted = <>; # data from a file is tainted

$a = $tainted; # now $a is also tainted

unlink $a; # fatal error!

Data can be untainted by selecting valid data

$tainted =˜ /(\w+)/; # select only word chars.

$a = $1; # now OK, $a is untainted

Also setup environment values: PATH IFS CDPATH ENV BASH_ENV

$ENV{PATH} = '/bin:/usr/bin:/usr/local/bin';

$ENV{IFS} = " \t\n\f";

delete @ENV{ qw/CDPATH ENV BASH_ENV/ }; #LX222D16T

Page 194: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-10

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 thoughcode, breakpoints, automatic actions, ...

Example:

$ perl -d myscript

$ perl -de 1

Loading DB routines from perl5db.pl version 1.0402

Emacs support available.

Enter h or �h h' for help.main::(-e:1): 1

DB<1>LX222D18T

Page 195: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-11

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 linesLX222D20T

Page 196: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-12

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

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

=end X LX222D22T

Page 197: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

13-13

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 documentationLX222D02T

Page 198: Linux, Perl - LX222VIS

Unit 14. Report Generation

Copyright IBM Corp. 1999, 2001 14-1

Page 199: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-2

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 placeholdersLX222E00T

Page 200: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-3

Understanding Report Formats

Perl started as a language for data manipulation and reporting

It has facilities to generate simple columnar reports with pageheadings

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 statementLX222E04T

Page 201: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-4

Report Formats

A report is declared in a program with a format statement

Formats are associated with filehandles and are usually given thesame name

Syntax:

format FORMATNAME =

report_layout

.LX222E06T

Page 202: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-5

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 theplaceholders

Each picture line with placeholders must be followed by a value line

� with a value for each placeholder

Example:

stock#: @###### quantity: @##

$stock, $quanLX222E08T

Page 203: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-6

A Report Example

format PICKLIST =

________________________________________

| |

| stock#: @###### quantity: @## |

$stock, $quan

| @<<<<<<<<<<<<<<<<<<<<<<<<<<< |

$desc

| row: @## col: @# bin: @# |

$row, $col, $bin

| price: @####.## store#: @### |

$price, $store

|______________________________________|

.LX222E10T

Page 204: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-7

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";

while ( <ORDERS> ) {

chomp;

($stock,$quan,$desc,$row,$col,$bin,$price,$store) =

split (/:/);

write PICKLIST ;

}LX222E12T

Page 205: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-8

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 filehandleLX222E14T

Page 206: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-9

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

Page 207: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-10

Report Format Special Variables

Several variables are used when report writing

All apply to the current default output filehandle

$˜ Body format name

$� Header format name

$% Report page number

$= Printable lines/page

$- Number of lines remaining on the pageLX222E18T

Page 208: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-11

Report Format Variables Example

# 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

Page 209: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-12

Report Layout Placeholders

There are four classes of placeholders:

Numeric

String

Multiple Line

ExpandableLX222E22T

Page 210: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-13

Numeric Variable Placeholders

Right justified with optional decimal point

Syntax:

@######.##

Example:

@###### @######.##

$stock, $stock * $value

Result:

250 307.50LX222E24T

Page 211: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-14

String Variable Placeholders

Three variations:

@<<<<<< left-justified

@>>>>>> right-justified

@|||||| centered

Example:

@<<<<<<<<<< @|||||||||| @>>>

scalar localtime, $title, $%LX222E26T

Page 212: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-15

Multi-line Variable Placeholders

Multi-line strings are normally truncated at the first newline

The multi-line placeholder prints multi-line strings “as-is” withouttruncation

Syntax:

@*

Example:

Description: @*

"This is a \nmulti-line\nparagraph."

Result:

Description: This is a

multi-line

paragraph.LX222E28T

Page 213: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-16

Variable Length Placeholders

Print as much as possible from the variable, removing data onceprinted

Example:

Desc: �<<<<<<<<<<<<<<<< $data

˜˜ �<<<<<<<<<<<<<<<< $data

LX222E30T

Page 214: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

14-17

Summary

� Understanding report formats

� Define a report format

� Executing a report format

� Filehandles in reports

� Format names

� Place holdersLX222E02T

Page 215: Linux, Perl - LX222VIS

Unit 15. Accessing Operating System Data

Copyright IBM Corp. 1999, 2001 15-1

Page 216: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-2

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 sequentiallyLX222F00T

Page 217: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-3

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";

foreach (sort keys %ENV) { # re-implement printenv

print "$_ = $ENV{$_}\n";

}LX222F04T

Page 218: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-4

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 startedLX222F06T

Page 219: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-5

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 thedata

Syntax:

pack(template, list)

unpack(template, expression)

Example:

@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

Page 220: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-6

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

&= |= �= <<= >>=

These operator treat their operands as bit-strings

16 | 2 is 18

00010000 | 00000010 00010010

"A" & "X" is "@"

01000001 & 01011000 01000000LX222F10T

Page 221: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-7

Obtaining Hostname Information

On systems with TCP/IP networking, Perl supports the standard socketlibrary interface

Example:

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

Page 222: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-8

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

Page 223: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-9

Password File Sequential Access

Syntax:

setpwent - initialize scan of password file

getpwent - return next entry

endpwent - terminate scan of password file

Example:

setpwent;

print "Username Shell Home\n";

while (@pw = getpwent) {

printf "%-8s %-10s %s\n", $pw[0], $pw[8], $pw[7];

}

endpwent;LX222F16T

Page 224: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-10

Accessing Group Info by Name or ID

Syntax:

getgrgid(GID)

getgrnam(group_name)

Example:

($name, $gpasswd, $gid, $gmembers) =

getgrgid(223) || getgrnam("perl") ;LX222F18T

Page 225: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-11

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:

setgrent;

while (@grp = getgrent) {

print $grp[0], "\n" if $grp[3] =˜ /\b$user\b/;}

endgrent;LX222F20T

Page 226: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-12

Time Related Functions

Syntax:

time

gmtime numeric_expression

localtime numeric_expression

Example:

print "Completed in ", time - $�T, " seconds.\n";

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

Page 227: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

15-13

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 sequentiallyLX222F02T

Page 228: Linux, Perl - LX222VIS

Unit 16. Running External Programs

Copyright IBM Corp. 1999, 2001 16-1

Page 229: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

16-2

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 anotherLX222G00T

Page 230: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

16-3

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!

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

Page 231: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

16-4

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 processingLX222G06T

Page 232: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

16-5

Run a Program and Capture Output

Backquotes do command substitution — the string is replaced bythe output of the command-line

Syntax:

� command-line �qx/command-line/

Example:

$osl = "The operating system is " . �ver� ;

foreach (qx/ls/) {

unlink $_;

}

($heading, @ps) = �ps� ;LX222G08T

Page 233: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

16-6

Creating Pipes to Other Programs

Filehandles can be pipes to, or from, programs

The position of the pipe symbol | in the filename determines themode

Syntax:

open(FILEHANDLE,"command-line |") ; # open for reading

open(FILEHANDLE,"| command-line") ; # open for writing

Example:

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

Page 234: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

16-7

Run a Program Overlaying the CurrentProgram

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";

exec 'ps', @args; # exec'd directly

die "$0: exec failed: $!\n";LX222G12T

Page 235: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

16-8

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 outSIGINT Interrupt. From Control-CSIGQUIT Interrupt and write core. From Control-\SIGTERM Terminate request. From kill <PID>

Signals are sent with kill

Syntax:

kill signal, list_of_PIDs

Example:

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

Page 236: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

16-9

Dealing With Signals

Assign to the %SIG hash to change the default signal effect

Examples:

$SIG{HUP} = 'IGNORE'; # ignore hangups

$SIG{INT} = 'DEFAULT'; # (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"; }

$debug = 0;

$SIG{USR1} = sub {$debug = 1;}; # reference to anonymous

$SIG{USR2} = sub {$debug = 0;}; # subroutineLX222G16T

Page 237: Linux, Perl - LX222VIS

C

op

yrigh

t IBM

Co

rp. 1999, 2001

16-10

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 anotherLX222G02T

Page 238: Linux, Perl - LX222VIS

����