Title: Perl Introduction
1Perl Introduction
2Perl 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
3How 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
4How to Obtain Perl (cont.)
- Compile Perl Source code
- Make executable visible to users
5Perl Support
- Perl Language
- Freeware
- Commercial versions
- Perl Support
- Corporate support
- Web pages
- Mailing lists
- Usenet news
- The Perl Journal
6Running 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
7Command 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
8Command 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
9Sample 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
10Basics
- ! Shebang
- Comments
- Statement termination
- , -e Operators
- ltSTDINgt Filehandles
- sFile Variables
- if Control structures
- chop, print Functions
11Review
- Perl Language
- How to Obtain Perl
- Running a Perl Program
- Command Line Operations
- Sample Perl Program
- Basics
12Data Types and Contexts
13Data 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)
14Scalar 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
15Contexts
- Scalar
- nCount _at_asNames
- List
- _at_asNames (Larry, Moe, Curly)
- Boolean
- if (nCount gt nMax)
- Void
- 1
- Interpolative
- print nCount nCount
16Quoted 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.
17Escape Sequences
- \n Newline
- \r Carriage return
- \t Horizontal tab
- \f Form feed
- \b Backspace
- \a Alert (bell)
- \e ESC character
- \cC Control-C
18Escape 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
19Escape 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
20Numeric 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
21List 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
22Array 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
23Opening 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
24Reading with ltgt
- Reading from File
- input ltMYFILEgt
- Reading from Command Line
- input ltgt
- Reading from Standard Input
- input ltgt
- input ltSTDINgt
- Example files.pl
25Review
- Data Types
- Scalars Examples
- Contexts
- Quoted Strings
- Numeric Scalars
- List Values
- Array Examples
- File Handles
26Statements
27Simple Statements
- Syntax
- statement keyword condition
- Keyword
- if
- unless
- while
- until
- Example
- print(Goodbye!\n) if sAns eq yes
- Example compound.pl
28Simple 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
29Compound Statements
- Syntax
- keyword (condition) statements
- Example
- if (sAns eq yes)
-
- print(Goodbye!\n)
-
30The 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
31The 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
32The 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
33The 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
34The 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
35The 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
36Loop 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
37Review
- Simple Statements
- Compound Statements
- if Statement
- while, until, for, foreach and do loops
- Loop control Statements
38Expressions
39Flow Control Operators
- Definition
- Examples
- do block_of_statements
- goto label
- last, last label
- next, next label
- redo, redo label
- Example labels.pl
40Operators
- Definition
- Breakdown
- File Test Operators
- Arithmetic Operators
- Comparison Operators
- Logical Operators
- Other Operators
41File 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
42File Test Operators (cont.)
- (Partial) List of File Test Operators
- -d
- -e
- -f
- -l
- -r
- Example filetest_operators.pl
43Arithmetic Operators
- Addition ()
- Subtraction (-)
- Multiplication ()
- Division (/)
- Assignment ()
44Arithmetic Operators (cont.)
- Exponentiation ()
- Remainder ()
- Unary Negation (-)
- Example calc.pl
- Example concat.pl
- Example email.pl
45Comparison Operators
- String and Numeric Comparison Operators
- Example ascii.pl, compare.pl
46Logical Operators
- Definition
- Examples
- Local and ()
- Logical or ()
- Logical not (!)
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
47Other Operators
- Bit-manipulation Operators
- Bitwise AND ()
- Bitwise OR ()
48Other Operators (cont.)
- Bit-manipulation Operators
- Bitwise XOR ()
- Bitwise NOT ()
- Shift Left (ltlt)
- Shift Right (gtgt)
- Example bitwise.pl
49Other 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
50Other 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
51Operator Precedence
52Operator Precedence (cont.)
53Review
- Flow Control Operators
- Operators
- File Test Operators
- Arithmetic Operators
- Operator Precedence
54More Expressions
55String Manipulation
- chop
- chop(VARIABLE)
- chop(LIST)
- index(STR, SUBSTR, POSITION)
- index(STR, SUBSTR)
- length(EXPR)
56String Manipulation (cont.)
- substr(EXPR, OFFSET, LENGTH)
- substr(EXPR, OFFSET)
- Example string.pl
57Conversion
- Time Conversion To GMT
- gmtime(EXPR)
- Time Conversion To Local Time
- localtime(EXPR)
- Example time.pl
58Conversion (cont.)
- Hexadecimal to Decimal
- hex(EXPR)
- Floating-Point to Integer
- int(EXPR)
59Pattern 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
60Pattern Matching (cont.)
- Special Characters in Patterns
- 1 or more occurrences of preceding character(s)
-
61Pattern 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?
- /\/
- /\/
- /\\/
62Pattern Matching (cont.)
- Pattern Anchoring
- or \A
- or \Z
- \b
- \B
63Pattern Matching (cont.)
64Pattern Matching (cont.)
- Character-Range Escape Sequence
- \d
- \D
- \w
- \W
- \s
- \S
65Pattern Matching (cont.)
- Matching any Character
- .
- Matching Specified Number of Occurrences
-
- Specifying Choices
66Pattern Matching (cont.)
- Special Character Precedence
- ()
- ?
- \b \B
67Pattern Matching (cont.)
- Pattern Matching Options Syntax
- /pattern/option
- Options
- g
- i
68Pattern Matching (cont.)
- Options
- m
- o
- s
- x
- Pattern Matching Location
- offset pos(string_to_match)
- Example pattern.pl
- Example position.pl
69Pattern Matching (cont.)
- Substitution
- s/pattern/replacement_pattern/
70Pattern Matching (cont.)
71Pattern Matching (cont.)
- Substitution Options
- e
- m
- o
- s
- x
72Pattern Matching (cont.)
- Translation Operator
- tr/string_1/string_2/
73Pattern Matching (cont.)
- Translation Operator Options
- c
- d
- s
- Example trdemo.pl
74Review
- String Manipulation
- Conversion
- Pattern Matching
75Lists and Arrays
76Arrays Generalities
- Perl Entities
- Scalar Value
- Scalar Variable
- List
- Array
- Definition
- Types of Arrays
- Numerical Subscripted (_at_)
- Associative ()
77Elements within Arrays
- Syntax
- element array n
- vs. _at_
78List and Array Syntax
- List Syntax
- (value_1, value_2, , value_n)
- Empty List
- ()
- Array Syntax
- _at_array list_of_variables
-
79Numerical Subscripted Arrays
- Definition
- Accessing a Numerical Subscripted Array
- Creating a Numerical Subscripted Array
80Numerical Subscripted Arrays (cont.)
- Copy to/from a Numerical Subscripted Array
- Adding Numerical Subscripted Array Elements
81Numerical Subscripted Arrays (cont.)
- Retrieving Length
- length_of_array _at_array
- Number of Entries in Array
- Last Index in Array
- last_index array
82Associative Arrays
- Definition
- Accessing an Associative Array
- Creating an Associative Array
83Associative Arrays (cont.)
- Copy to/from an Associative Array
- Adding/Deleting Associative Array Elements
84Associative 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)
85Associative Arrays (cont.)
- Looping Using Associative Arrays
- Example arrays.pl
- Example env.pl
86List and Array Functions
- Removing Characters
- chop (_at_array)
- Merging Elements
- joined_list join (_at_array)
- joined_list join (.,_at_array) use . As
join character
87List and Array Functions (cont.)
- Splitting String
- split /PATTERN/, EXPR, LIMIT
- split /PATTERN/, EXPR
- split /PATTERN/
- split
88Array Library Functions
- shift _at_array
- shift
- unshift _at_array, list
89Array Library Functions (cont.)
- push _at_array, list
- pop _at_array
- pop
- Example function.pl
90Slices
- Extension of Accessing Single Array Element
- Examples
- _at_subarray _at_array 0,2
- _at_subarray _at_array 0..2
- Overlapping Array Slices
91Sorting
- Sorting Elements
- _at_sorted_list sort (_at_array)
- Reversing Order
- _at_reversed_list reverse (_at_array)
- Example sorts.pl
92Review
- Numerical Subscripted Arrays
- Associative Arrays
- List and Array Functions
- Array Library Functions
- Slices
- Sorting
93Reading from and Writing to Files
94Opening and Closing Files
- open
- Syntax open (FH1, file1)
- Read (lt)
- Write (gt)
- Read and Write (gt or lt)
- Append (gtgt)
- close
- Syntax Close (FH1)
95eof
- 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
96Standard Files
- Standard Input
- STDIN
- Standard Output
- STDOUT
- Standard Error
- STDERR
97Reading with ltgt
- Reading from File
- input ltMYFILEgt
- Reading from Command Line
- input ltgt
- Reading from Standard Input
- input ltgt
- input ltSTDINgt
98Reading with ltgt (cont.)
- Reading into Array Variable
- _at_an_array ltMYFILEgt
- _at_an_array ltSTDINgt
- _at_an_array ltgt
99File Operations
- File-attribute Functions
- Performing Relocation
- rename
- unlink
100File Operations (cont.)
- Creating Links
- link
- symlink
- readlink
101File Operations (cont.)
- Changing File Permissions
- chmod
- chown
- umask
102File 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)
-
103File Status Determination (cont.)
- (Partial) List of File Test Operators
- -d
- -e
- -f
- -l
- -r
- -s
- -w
- -x
- -z
104Directory Manipulation
- Definition
- Examples
- mkdir
105Directory Manipulation (cont.)
106Directory Manipulation (cont.)
- Examples
- opendir
- readdir
- closedir
- Example readfile.pl
- Example dirread.pl
107I/O Operations
- Read and Write
- read
- sysread
108I/O Operations (cont.)
- Read and Write
- syswrite
- getc
- binmode
109ARGV and ltgt
- ARGV
- _at_ARGV
- ltgt and _at_ARGV
- Example readargs.pl
- Syntax perl readargs.pl tst.txt tst2.txt tst3.txt
110Review
- Reading with ltgt
- File Operations
- File Status Determination
- Directory Manipulation
- I/O Operations
- ARGV and lt gt