Perl Introduction - PowerPoint PPT Presentation

1 / 110
About This Presentation
Title:

Perl Introduction

Description:

Functions from, C, sed, awk, and sh. Interpretive vs. Compiled Language. WWW Information ... nNbr1 = int 10 / 3; #Truncates. Example: numerics.pl. Page 21. List Values ... – PowerPoint PPT presentation

Number of Views:44
Avg rating:3.0/5.0
Slides: 111
Provided by: brandon66
Category:

less

Transcript and Presenter's Notes

Title: Perl Introduction


1
Perl Introduction
2
Perl Language
  • Practical Extraction and Report Language
  • Perl Language
  • Interpreted Language
  • Functions from, C, sed, awk, and sh
  • Interpretive vs. Compiled Language
  • WWW Information
  • http//www.perl.com

3
How to Obtain Perl
  • Get Perl Through WWW Using FTP
  • ftp ftp.CPAN.org
  • Name (ftp.CPAN.orgCPAN) anonymous
  • ftpgt cd pub/perl/CPAN/src
  • ftpgt binary
  • ftpgt get latest.tar.gz
  • ftpgt quit
  • Uncompress and Unpack
  • gunzip lt latest.tar.gz tar xvf -
  • cd perl5.004
  • sh configure make make test make
    install

4
How to Obtain Perl (cont.)
  • Compile Perl Source code
  • Make executable visible to users

5
Perl Support
  • Perl Language
  • Freeware
  • Commercial versions
  • Perl Support
  • Corporate support
  • Web pages
  • Mailing lists
  • Usenet news
  • The Perl Journal

6
Running a Perl Program
  • Can be run from the command line
  • perl -e print Hello, world!\n
  • Can be run from a script
  • vi hello.pl
  • !/usr/bin/perl
  • print Hello, World!\n
  • chmod x hello.pl
  • hello.pl
  • Example hello.pl

7
Command Line Operations
  • Options on Command Line
  • perl options program
  • Options in a Script
  • ! /usr/bin/perl options
  • ! /usr/local/bin/perl in the Alcatel Environment
  • Options
  • -c Check syntax without execution
  • -d Run under Perl debugger
  • -e Execute line of script from command line
  • -h Summary of command line actions

8
Command Line Operations (cont.)
  • Options
  • -l Automatic line-end processing
  • -n Runs scrip for each input line like sed -n,
    awk
  • -p Same as -n above but outputs result like sed
  • -v Prints version and patch level of Perl
  • -w Prints syntax warnings
  • Example options.pl
  • Sample execution perl -l011 options.pl tst.txt

9
Sample Perl Program
  • !/usr/bin/perl -w
  • print Enter a filename Prompt the user
  • sFile ltSTDINgt Wait for input
  • chop(sFile) Remove the newline
  • if (-e sFile) Test file existence
  • print sFile exists!\n
  • else
  • print sFile not found!\n
  • Example files.pl
  • Example chomp.pl

10
Basics
  • ! Shebang
  • Comments
  • Statement termination
  • , -e Operators
  • ltSTDINgt Filehandles
  • sFile Variables
  • if Control structures
  • chop, print Functions

11
Review
  • Perl Language
  • How to Obtain Perl
  • Running a Perl Program
  • Command Line Operations
  • Sample Perl Program
  • Basics

12
Data Types and Contexts
13
Data Types
  • Scalars
  • nToday 3
  • print Today is asWeeknToday
  • Arrays of Scalars
  • _at_asWeek (Sun, Mon, Tue,
  • Wed, Thu, Fri, Sat)
  • Associative Arrays of Scalars (Hash)
  • hnWeek (Sun,0, Mon,1, Tue,2, Wed,
    3,Thu,4, Fri,5, Sat,6)

14
Scalar Examples
  • nToday 3 Simple scalar assignment
  • asWeek3 Wed 4th element of array
  • hnWeekWed 3 One value from hash
  • nLast asWeek Last index of array
  • nTotal _at_asWeek Total count of array
  • Example
  • _at_asWeek (Sun, Mon, Tue, Wed, Thu,
    Fri, Sat)
  • nLast asWeek nLast 6
  • nTotal _at_asWeek nTotal 7

15
Contexts
  • Scalar
  • nCount _at_asNames
  • List
  • _at_asNames (Larry, Moe, Curly)
  • Boolean
  • if (nCount gt nMax)
  • Void
  • 1
  • Interpolative
  • print nCount nCount

16
Quoted Strings
  • Double Quoted
  • sStr1 nNbr1 nNbr1\n
  • Single Quoted
  • sStr1 nNbr1 nNbr1\n
  • Differences
  • Scalar Variable Interpolation
  • Backslash Character \
  • print nNbr1, \n Quotes not needed for
    scalars.
  • print nNbr1\n More readable.

17
Escape Sequences
  • \n Newline
  • \r Carriage return
  • \t Horizontal tab
  • \f Form feed
  • \b Backspace
  • \a Alert (bell)
  • \e ESC character
  • \cC Control-C

18
Escape Sequences - Case
  • \u Next Character Uppercase
  • \l Next Character Lowercase
  • \U All Following Characters Uppercase
  • \L All Following Characters Lowercase
  • \Q Backslash All Non-AlphaNumeric
  • \E End \U, \L, or \Q

19
Escape Sequence Examples
  • Examples
  • sTxt lOWEr aND UpperCase
  • print(Uppercase \UsTxt\E\n)
  • print(Lowercase \LsTxt\E\n)
  • print(As a sentence \L\usTxt\E\n)
  • Output
  • Uppercase LOWER AND UPPERCASE
  • Lowercase lower and uppercase
  • As a sentence Lower and uppercase

20
Numeric Scalars
  • Integers Stored in Float Registers
  • Floating Point Values
  • .00045 45000
  • 4.5e-4 4.5e4
  • Forcing Integer Interpretation
  • Block scope
  • use integer nNbr1 10 / 3
  • Single line
  • nNbr1 int 10 / 3 Truncates
  • Example numerics.pl

21
List Values
  • Separate individual values by commas
  • Usually enclosing the list in parentheses
  • Null list is represented by ()
  • List context a list is its values in order
  • _at_anTst (1, 2, 3) Initialize an array
  • Scalar context a list is the value of last
    element
  • nTst (one, two, three) nTst is
    three
  • Expression that return values may be in a list

22
Array Examples
  • Initialize an array
  • _at_anScores (95, 90, 92)
  • Assign scalar count and numeric array
  • nCount _at_anScores (95, 90, 92)
  • Slice of an array is named with _at_
  • _at_anSubArray _at_anScores1..2
  • Slice of a hash is named with _at_
  • _at_anDays _at_hnWeekMon, Wed, Fri
  • Example lists.pl
  • Example hashs.pl

23
Opening Closing Files
  • Syntax
  • open(FILEHANDLE, mode filename)
  • close(FILEHANDLE)
  • Modes
  • Read-only - file1 or ltfile1
  • Write-only - gtsFilename
  • Read/Write - ltfile1 or gt file1
  • Append-only - gtgtfile1
  • Read/Append - gtgt file1 ver. 5.004

24
Reading with ltgt
  • Reading from File
  • input ltMYFILEgt
  • Reading from Command Line
  • input ltgt
  • Reading from Standard Input
  • input ltgt
  • input ltSTDINgt
  • Example files.pl

25
Review
  • Data Types
  • Scalars Examples
  • Contexts
  • Quoted Strings
  • Numeric Scalars
  • List Values
  • Array Examples
  • File Handles

26
Statements
27
Simple Statements
  • Syntax
  • statement keyword condition
  • Keyword
  • if
  • unless
  • while
  • until
  • Example
  • print(Goodbye!\n) if sAns eq yes
  • Example compound.pl

28
Simple Statements (Cont.)
  • Example to Copy Files
  • !/usr/bin/perl
  • die(Unable to open input. !\n) unless
    open(INFILE, infile)
  • die(Unable to open output. !\n) unless
    open(OUTFILE, gtoutfile)
  • print(OUTFILE sLine) while
  • (sLine ltINFILEgt)
  • close(INFILE)
  • close(OUTFILE)
  • Example opens.pl

29
Compound Statements
  • Syntax
  • keyword (condition) statements
  • Example
  • if (sAns eq yes)
  • print(Goodbye!\n)

30
The if statement
  • Syntax
  • if (CONDITION) BODY
  • elsif (CONDITION) BODY
  • else BODY
  • Example
  • if (sDay eq Sun) nDay 0
  • elsif (sDay eq Mon) nDay 1
  • ...
  • else print(Invalid day!\n)
  • Example tests.pl

31
The while statement
  • Syntax
  • while (CONDITION) BODY
  • Example
  • i 0 Initialize loop variable.
  • while (i lt 10) Test.
  • print(Iteration i\n)
  • i Increment.
  • Example whileloop.pl

32
The until statement
  • Syntax
  • until (CONDITION) BODY
  • Example
  • s Initialize loop var
  • until (s eq q) Test.
  • print(Enter word, q to quit )
  • chop(s ltSTDINgt) Change loop var
  • sLine . s

33
The for statement
  • Syntax
  • for (START STOP ACTION) BODY
  • Initially execute START statements once.
  • Repeatedly execute BODY until STOP is false.
  • Execute ACTION after each iteration.
  • Example
  • for (i0 ilt10 i)
  • print(Iteration i\n)
  • Example loops.pl

34
The foreach statement
  • Syntax
  • foreach SCALAR ( ARRAY ) BODY
  • Assign ARRAY element to SCALAR.
  • Execute BODY.
  • Repeat for each element in ARRAY.
  • Example
  • asTmp qw(One Two Three)
  • foreach s (_at_asTmp)s . sy
  • print(_at_asTmp) Onesy Twosy Threesy
  • Example foreach.pl

35
The do statement
  • Syntax
  • do BODY while CONDITION
  • do BODY until CONDITION
  • Example
  • do
  • sLine . s if s
  • print(Enter word, q to quit )
  • chop(s ltSTDINgt) Change loop var
  • until s eq q Test

36
Loop Control Statements
  • Last
  • Exit loop.
  • Next
  • Control passes to beginning of loop (executing
    the for increment statement) to begin another
    iteration.
  • Redo
  • Begin another loop iteration (bypass for
    increment).
  • Continue
  • Used with while to avoid infinite loop when next
    statement causes for increment to be bypassed.
  • Examples loopctrl.pl, split.pl

37
Review
  • Simple Statements
  • Compound Statements
  • if Statement
  • while, until, for, foreach and do loops
  • Loop control Statements

38
Expressions
39
Flow Control Operators
  • Definition
  • Examples
  • do block_of_statements
  • goto label
  • last, last label
  • next, next label
  • redo, redo label
  • Example labels.pl

40
Operators
  • Definition
  • Breakdown
  • File Test Operators
  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Other Operators

41
File Test Operators
  • Definition
  • Syntax
  • -x expression
  • Examples
  • not -e infile or warn
  • File infile exists\n
  • if (-e outfile)
  • die (Output file outfile already exists\n)
  • Example test_operator.pl

42
File Test Operators (cont.)
  • (Partial) List of File Test Operators
  • -d
  • -e
  • -f
  • -l
  • -r
  • Example filetest_operators.pl
  • -s
  • -w
  • -x
  • -z

43
Arithmetic Operators
  • Addition ()
  • Subtraction (-)
  • Multiplication ()
  • Division (/)
  • Assignment ()

44
Arithmetic Operators (cont.)
  • Exponentiation ()
  • Remainder ()
  • Unary Negation (-)
  • Example calc.pl
  • Example concat.pl
  • Example email.pl

45
Comparison Operators
  • String and Numeric Comparison Operators
  • Example ascii.pl, compare.pl

46
Logical Operators
  • Definition
  • Examples
  • Local and ()
  • Logical or ()
  • Logical not (!)
  • or
  • and
  • not
  • xor

a
ab
b
ab
!a
!(ab)
0
0
0
0
1
1
0
0
1
1
1
1
1
0
0
1
0
1
1
1
1
1
0
0
47
Other Operators
  • Bit-manipulation Operators
  • Bitwise AND ()
  • Bitwise OR ()

48
Other Operators (cont.)
  • Bit-manipulation Operators
  • Bitwise XOR ()
  • Bitwise NOT ()
  • Shift Left (ltlt)
  • Shift Right (gtgt)
  • Example bitwise.pl

49
Other Operators (cont.)
  • Assignment Operators
  • Auto-Increment and Auto-Decrement
  • --
  • Example other.pl
  • a15ca - 15 a16, c0
  • a15ca - 15 a16, c1
  • a15c--a 15 a14, c210
  • a15ca-- 15 a14, c225

50
Other Operators (cont.)
  • String Concatenation Operator (.)
  • String Repetition Operator (x)
  • Comma Operator (,)
  • Conditional Operator (? and )
  • Example the following are the same
  • if (test 0)
  • result 10
  • else
  • result 5
  • result test 0 ? 10 5

51
Operator Precedence
52
Operator Precedence (cont.)
53
Review
  • Flow Control Operators
  • Operators
  • File Test Operators
  • Arithmetic Operators
  • Operator Precedence

54
More Expressions
55
String Manipulation
  • chop
  • chop(VARIABLE)
  • chop(LIST)
  • index(STR, SUBSTR, POSITION)
  • index(STR, SUBSTR)
  • length(EXPR)

56
String Manipulation (cont.)
  • substr(EXPR, OFFSET, LENGTH)
  • substr(EXPR, OFFSET)
  • Example string.pl

57
Conversion
  • Time Conversion To GMT
  • gmtime(EXPR)
  • Time Conversion To Local Time
  • localtime(EXPR)
  • Example time.pl

58
Conversion (cont.)
  • Hexadecimal to Decimal
  • hex(EXPR)
  • Floating-Point to Integer
  • int(EXPR)

59
Pattern Matching
  • Definition of Pattern
  • Match Operators
  • (bind operator)
  • !
  • Example
  • bResultsVar/aAb/
  • bResult0 if there is no match, otherwise
    bResult1
  • bResultsVar!/aAb/
  • bResult0 if there is a match, otherwise
    bResult1

60
Pattern Matching (cont.)
  • Special Characters in Patterns
  • 1 or more occurrences of preceding character(s)

61
Pattern Matching (cont.)
  • Special Characters in Patterns
  • 0 or more occurrences of preceding
    character(s)
  • ? 1 or 1 occurrences of preceding character(s)
  • Special Character Escape Sequence (\)
  • Question What do the following patterns match?
  • /\/
  • /\/
  • /\\/

62
Pattern Matching (cont.)
  • Pattern Anchoring
  • or \A
  • or \Z
  • \b
  • \B

63
Pattern Matching (cont.)
  • Excluding Alternatives

64
Pattern Matching (cont.)
  • Character-Range Escape Sequence
  • \d
  • \D
  • \w
  • \W
  • \s
  • \S

65
Pattern Matching (cont.)
  • Matching any Character
  • .
  • Matching Specified Number of Occurrences
  • Specifying Choices

66
Pattern Matching (cont.)
  • Special Character Precedence
  • ()
  • ?
  • \b \B

67
Pattern Matching (cont.)
  • Pattern Matching Options Syntax
  • /pattern/option
  • Options
  • g
  • i

68
Pattern Matching (cont.)
  • Options
  • m
  • o
  • s
  • x
  • Pattern Matching Location
  • offset pos(string_to_match)
  • Example pattern.pl
  • Example position.pl

69
Pattern Matching (cont.)
  • Substitution
  • s/pattern/replacement_pattern/

70
Pattern Matching (cont.)
  • Substitution Options
  • g
  • i

71
Pattern Matching (cont.)
  • Substitution Options
  • e
  • m
  • o
  • s
  • x

72
Pattern Matching (cont.)
  • Translation Operator
  • tr/string_1/string_2/

73
Pattern Matching (cont.)
  • Translation Operator Options
  • c
  • d
  • s
  • Example trdemo.pl

74
Review
  • String Manipulation
  • Conversion
  • Pattern Matching

75
Lists and Arrays
76
Arrays Generalities
  • Perl Entities
  • Scalar Value
  • Scalar Variable
  • List
  • Array
  • Definition
  • Types of Arrays
  • Numerical Subscripted (_at_)
  • Associative ()

77
Elements within Arrays
  • Syntax
  • element array n
  • vs. _at_

78
List and Array Syntax
  • List Syntax
  • (value_1, value_2, , value_n)
  • Empty List
  • ()
  • Array Syntax
  • _at_array list_of_variables

79
Numerical Subscripted Arrays
  • Definition
  • Accessing a Numerical Subscripted Array
  • Creating a Numerical Subscripted Array

80
Numerical Subscripted Arrays (cont.)
  • Copy to/from a Numerical Subscripted Array
  • Adding Numerical Subscripted Array Elements

81
Numerical Subscripted Arrays (cont.)
  • Retrieving Length
  • length_of_array _at_array
  • Number of Entries in Array
  • Last Index in Array
  • last_index array

82
Associative Arrays
  • Definition
  • Accessing an Associative Array
  • Creating an Associative Array

83
Associative Arrays (cont.)
  • Copy to/from an Associative Array
  • Adding/Deleting Associative Array Elements

84
Associative Arrays (cont.)
  • Two Numerical Arrays for Associative Array
  • Index
  • Values
  • Associative Array Index
  • keys (array)
  • _at_keys_list sort keys (array)
  • Associative Array Values
  • values (array)
  • _at_values_list sort values (array)

85
Associative Arrays (cont.)
  • Looping Using Associative Arrays
  • Example arrays.pl
  • Example env.pl

86
List and Array Functions
  • Removing Characters
  • chop (_at_array)
  • Merging Elements
  • joined_list join (_at_array)
  • joined_list join (.,_at_array) use . As
    join character

87
List and Array Functions (cont.)
  • Splitting String
  • split /PATTERN/, EXPR, LIMIT
  • split /PATTERN/, EXPR
  • split /PATTERN/
  • split

88
Array Library Functions
  • shift _at_array
  • shift
  • unshift _at_array, list

89
Array Library Functions (cont.)
  • push _at_array, list
  • pop _at_array
  • pop
  • Example function.pl

90
Slices
  • Extension of Accessing Single Array Element
  • Examples
  • _at_subarray _at_array 0,2
  • _at_subarray _at_array 0..2
  • Overlapping Array Slices

91
Sorting
  • Sorting Elements
  • _at_sorted_list sort (_at_array)
  • Reversing Order
  • _at_reversed_list reverse (_at_array)
  • Example sorts.pl

92
Review
  • Numerical Subscripted Arrays
  • Associative Arrays
  • List and Array Functions
  • Array Library Functions
  • Slices
  • Sorting

93
Reading from and Writing to Files
94
Opening and Closing Files
  • open
  • Syntax open (FH1, file1)
  • Read (lt)
  • Write (gt)
  • Read and Write (gt or lt)
  • Append (gtgt)
  • close
  • Syntax Close (FH1)

95
eof
  • End-of-file
  • eof indicates end-of-file for current file
  • eof() indicates end of all files read
  • Example eof.pl
  • Syntax perl eof.pl tst.txt tst1.txt

96
Standard Files
  • Standard Input
  • STDIN
  • Standard Output
  • STDOUT
  • Standard Error
  • STDERR

97
Reading with ltgt
  • Reading from File
  • input ltMYFILEgt
  • Reading from Command Line
  • input ltgt
  • Reading from Standard Input
  • input ltgt
  • input ltSTDINgt

98
Reading with ltgt (cont.)
  • Reading into Array Variable
  • _at_an_array ltMYFILEgt
  • _at_an_array ltSTDINgt
  • _at_an_array ltgt

99
File Operations
  • File-attribute Functions
  • Performing Relocation
  • rename
  • unlink

100
File Operations (cont.)
  • Creating Links
  • link
  • symlink
  • readlink

101
File Operations (cont.)
  • Changing File Permissions
  • chmod
  • chown
  • umask

102
File Status Determination
  • Definition
  • Syntax
  • -x expression
  • Examples
  • if (-e infile)
  • die (File infile exists, but can not be
    opened.\n)
  • if (-e outfile)
  • die (Output file outfile already exists.\n)

103
File Status Determination (cont.)
  • (Partial) List of File Test Operators
  • -d
  • -e
  • -f
  • -l
  • -r
  • -s
  • -w
  • -x
  • -z

104
Directory Manipulation
  • Definition
  • Examples
  • mkdir

105
Directory Manipulation (cont.)
  • Examples
  • chdir
  • rmdir

106
Directory Manipulation (cont.)
  • Examples
  • opendir
  • readdir
  • closedir
  • Example readfile.pl
  • Example dirread.pl

107
I/O Operations
  • Read and Write
  • read
  • sysread

108
I/O Operations (cont.)
  • Read and Write
  • syswrite
  • getc
  • binmode

109
ARGV and ltgt
  • ARGV
  • _at_ARGV
  • ltgt and _at_ARGV
  • Example readargs.pl
  • Syntax perl readargs.pl tst.txt tst2.txt tst3.txt

110
Review
  • Reading with ltgt
  • File Operations
  • File Status Determination
  • Directory Manipulation
  • I/O Operations
  • ARGV and lt gt
Write a Comment
User Comments (0)
About PowerShow.com