Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Objectives
Agenda
Part 1 (1:30PM to 2:45PM)
Introduction to Perl
Types of Variables
I/O Functions
Operators
String and formatting strings
Selectional, iterational and
miscellaneous control statements
Data Structures
Arrays and various operations on arrays
Hashes and various operations on
hashes
Functions:
Subroutines
Command line arguments
Perl Introduction
Perl Interpreter
Converts the scripts in to a parse tree and executes
immediately
Internally Perl maintains a byte code for execution
Known as interpreter/ compiler
PERL - Variables
Scalar Variables
Simple variables containing an element, either a number or a
string
Defined by $ symbol
Array
List of scalar variables
Defined by @ symbol
Hashes
Similar to arrays
Each item is identified by a key value
Defined by % symbol
PERL - Lists
print
Unformatted output statement which can print a string, Number or a
List
Default outputs to STDOUT, can be redirected to STDERR or a File
Returns true if successful else false [1 represents true]
print List
print FILEHANDLE List
printf
Formatted output statement
By defaults outputs to STDOUT. Can be redirected to STDERR or a File
printf Format, List
printf FILEHANDLE, Format, List
warn
Outputs a message on the STDERR stream (unbuffered)
Used to trace error when STDOUT is redirected
Program is neither terminated nor an exception is thrown
warn Message
Linux User Group at San Jose State
University
10
PERL - Operators
Assignment Operator
Auto increment and decrement operators
Additive operators
Multiplicative operators
Exponentiation Operator
Relational Operators
Logical Operators
Range Operator
Binding Operator
Arrow operator
File I/O Operator
11
12
Relational Operators
Operating on Numeric data
<, <=, >, >=, ==, !=,
- Operating on String data
lt
less than E.g. ($Myname lt $YourName)
gt
greater than
le
less than or equal to
ge
greater than or equal to
eq
equal to
ne
not equal to
cmp
compare (returns -1, 0 , 1)
- Logical Operator
AND - && or and
OR - || or or
NOT - not
Linux User Group at San Jose State
University
13
14
Input operator
<STDIN> or <>
Read input from the user including \n from the user
chomp operator can be used for removing the \n character
By default input is stored in a default variable $_
chomp
Usually used to discard the \n character at the end of input
string
15
PERL - Strings
16
17
18
19
Branching Statements
if
if else
if elsif
Looping Statements
while / until
do while/ until
for
foreach
Miscellaneous Control Statements
last, next, redo
Expression modifiers
exit, die
20
21
while loop
while (condition) {
#while block statements
}
Control comes out of the loop when the condition is FALSE
until loop
until (condition) {
#until block statements
}
Control comes out of the loop when the condition is TRUE
22
do while loop
do{
#while block statements
}while (condition)
Control comes out of the loop when the condition is FALSE
do until loop
do {
#until block statements
}until (condition)
Control comes out of the loop when the condition is TRUE
23
for
for(init expr ; condition ; increment/decrement ) {
#for block
}
foreach
mostly used when iteration has to be done for different values
in a list
foreach Variable (LIST) {
#Block of Statements
}
24
continue
flow control statement follows while or foreach loop
continue block will be executed after every successful
completion of an iteration
next
used to continue with the next iteration of the loop by stopping
current iteration
cannot be used in side do-while/do-until loop
if continue block is present it will also be executed
redo
restarts the loop without evaluating the condition again
continue block is not executed, if present
last
exits the loop
continue block is not executed, if present
25
exit
used to terminate the execution of a script
exit 0 denotes exit on success and exit 1 denotes exit on error
cannot display error messages while exiting
$Choice=<STDIN>
if ($Choice==4) { exit 0};
die
displays the error message to STDERR stream
and terminates the execution of a script
copy($TargetFile,$SourceFile) or die File cannot be copied
26
PERL - Arrays
Set of scalar values
Dynamically grows/shrinks when ever required
Can store dissimilar data types
Prefixed with @ symbol
Un-initialized locations and locations beyond the end of array
will be undef
Can be initialized using
List
qw operator
Repetition operator (X)
Range operator (..)
Individual locations
27
28
29
30
PERL Hashes
Hashes
Unordered collection of values
Each element is linked to a key, which uniquely identifies that
element
Any element from the hash can be retrieved, added, deleted using
the key
A hash variable is prefixed with %
Also called as associative arrays
Accessing elements
Elements can be retrieved using key
$RetrievedElement = $Hash{Key};
Adding new elements
$Hash{ new key}= new element
Changing the existing elements
$Hash{key} = new element
Linux User Group at San Jose State
University
31
32
http://perldoc.perl.org/perldsc.html
33
34
Metacharacters
Dot (.) is a wildcard character - it matches any single character
except a newline (which is represented by "\n")
/b.t/ will match bat, bet, bit, but etc. It will not match bt or boat
etc.
A backslash in front of any metacharacter makes it non-special.
/3\.14159/ doesn't have a wildcard character.
Star (*) is a wildcard character it matches the preceding character
zero or more times
/perl\t*script/ matches any number of tab characters between perl
and script. i.e. it matches perl\tscript" with one tab, or
"perl\t\tscript" with two tabs, or perl\t\t\tscript" with three tabs,
or even perlscript" with nothing in between at all.
Linux User Group at San Jose State
University
35
Metacharacters
Plus (+) is to match the preceding character one or more times
/perl +script/ matches if perl and script are separated only by
spaces. This pattern won't match perlscript, since the plus
matches only if there are one or more spaces between the two
words.
Question mark ("?") means that the preceding character is optional
/perl ? script/ matches it perl and script are separated by one space
or no space. This will match perl script as well as perlscript.
Parentheses ("( )") may be used for grouping
/(perl)+/ matches strings like perlperlperl
The vertical bar (|), often pronounced "or" means that either the left
side may match, or the right side
/unix|perl/ will match any string that mentions unix or perl
Linux User Group at San Jose State
University
36
Character class
a list of possible characters inside square brackets ([]),
matches any single character from within the class.
[abcwxyz] may match any one of the seven characters.
[a-zA-Z] may match any of the alphabets (both uppercase
and lowercase).
A caret (^) at the start of the character class negates it.
[^def] will match any single character except d, e or
f.
[\d] or [0-9] will match any digit
[\w] is a shortcut for any "word" character:
[\w] or [A-Za-z0-9_] will match any word
\s is a shortcut for white space character
37
38
39
PERL - Subroutines
40
Subroutine Declaration
sub MySubroutine()
MySubroutine accepts
sub MySubroutine($)
MySubroutine accepts
sub MySubroutine($$)
MySubroutine accepts
sub MySubroutine(@)
MySubroutine accepts
sub MySubroutine(%)
MySubroutine accepts
sub MySubroutine($@)
MySubroutine accepts
argument
sub MySubroutine($;$)
MySubroutine accepts
argument is optional
no arguments
one scalar argument
2 scalar arguments
an array as an argument
a hash reference as an argument
a scalar value and an array as
2 arguments, where the second
41
42
Reference Variable
Reference variable store the reference (address) of the
variables
Variables can be directly accessed using reference variables
Reference to a scalar
Command line arguments
Command line arguments are stored in a built in array @ARGV
when a perl script is executed
43
Example
word processing application might save the text in a linked list
or some other data structure when the application is running,
but when the application is terminated the contents of the
linked list need to stored in a file
44
Opening a File
open FILEHANDLE, FileName
Returns true (1) if successfully opened, false (0) otherwise
open (MyFileHandle,MyData.txt)
File will be opened for input if file name is prefixed by <
open (MyFileHandle,<MyData.txt)
File will be opened for output if the file name is prefixed by >
If the file exists contents will be erased
If the file doesnt exists new file will be created
open (MyFileHandle,>MyData.txt)
File will be opened for appending if the the file name is prefixed by
>>
If the file doesnt exist new file will be created
open (MyFileHandle,>>MyData.txt)
Linux User Group at San Jose State
University
45
Closing a File
Closing a file will transfer the un buffered data to the file
Returns true(1) if successful, false(0) otherwise
close FileHandle
Linux User Group at San Jose State
University
46
47
Questions
48