Professional Documents
Culture Documents
Introduction To Perl 2009
Introduction To Perl 2009
Agenda
Day-1 Introduction to Perl Variables Operators Array and Hash Functions Conditions and Loop Operators Day-2 Subroutines File Operations and IO Regular Expressions Perl Built in functions Day-3 Test
2 2/22/2012
Confidential McAfee Internal Use Only
Programming Methodologies
Structured or Method based
C Perl
Object Oriented
C++ Perl
Event Based
C# VB
2/22/2012
What is Perl ?
What is Perl ?
Perl stands for Practical Extraction and Reporting Language. Created in 1987 by Larry Wall. Inspired from Unix like languages like Sed, Awk and Shell Script. Most Perl Modules and scripts are platform independent. C-Like syntax. Perl is a freeware and open source.
2/22/2012
Slogan!!
2/22/2012
2/22/2012
Variables
Variables are storage containers for numbers, strings, and compound structures. Perl supports three types of variables: Scalars Arrays Hashes A variable name can be up to 255 characters. A variable name cannot start with a number e.g. $64bitint (leading numbers not legal)
10
2/22/2012
Variables (contd..)
A minus sign is not legal in the variable name e.g. $file-handle (minus sign not legal) Variable name cannot have special characters other than underscore(_) e.g. $excangerateto (pound symbol not legal) Here are some valid scalar variable names: $A_Scalar_Variable $scalarNo8 $_private_scalar
11
2/22/2012
Scalars ($)
Scalars
Scalar variables store a single value. They are prefixed with a $. Consider this example: $counter $string=Hello world; $string=Hello World; $string=123; $string=123.456;
13
2/22/2012
Arrays (@)
Arrays
An array is an indexed list of values with a consistent order. Names of arrays are prefixed with @. Examples of Arrays @first_array = (1, 2, 3, 4); @second_array = ('one', '2', 'three', '4', '5');
@a = qw(fred barney betty wilma);
15
2/22/2012
Hashes (%)
Hashes
Hashes are tables of key-value pairs. They are also called associative arrays. For example: %hash = ('Mouse', 'Jerry', 'Cat', 'Tom', 'Dog', 'Spike');
17
2/22/2012
Values Grabs the values from the hash @values = values(%hash); Keys Returns a list consisting of all the keys of the named hash. @keys = keys %hash; The keys are returned in an apparently random order, but it is the same order as either the values().
19
2/22/2012
20
2/22/2012
21
2/22/2012
delete
delete LIST Deletes the specified keys and associated values from a hash, or the specified elements from an array. The operation works on individual elements or slices. For example: delete $array[0]; Also note that when deleting an array item, only the items value is emptied; it doesnt remove the item from the list or close the gap between the preceding and subsequent item(s).
22
2/22/2012
each
each HASH In a list context, returns a two-element list referring to the key and value for the next element of a hash, allowing you to iterate over it. In a scalar context, returns only the key for the next element in the hash. Information is returned in a random order.
23
2/22/2012
exists
exists EXPR Returns true if the specified hash key exists, regardless of the corresponding value, even if its undef. Returns in Scalar Context 0 if hash element or array index does not exist and 1 if hash element or array index exists.
24
2/22/2012
join
join EXPR, LIST Combines the elements of LIST into a single string using the value of EXPR to separate each element. It is effectively the opposite of split. Note that EXPR is only interpolate between pairs of elements in LIST; it will not be placed either before the first or after the last element in the string. To join together strings without a separator, supply an empty string rather than undef.
25
2/22/2012
reverse
reverse LIST In a list context, returns the elements of LIST in reverse order. In a scalar context, returns a concatenated string of the values of LIST, with all bytes in opposite order. Returns in Scalar Context String Returns in List Context List
26
2/22/2012
scalar
scalar EXPR Forces the evaluation of EXPR to be in scalar context, even if it would normally work in list context
27
2/22/2012
splice
splice ARRAY, OFFSET, LENGTH, LIST splice ARRAY, OFFSET, LENGTH splice ARRAY, OFFSET Removes the elements of ARRAY from the element OFFSET for LENGTH elements, replacing the elements removed with LIST, if specified. If LENGTH is omitted, removes everything from OFFSET onwards.
28
2/22/2012
Operators
Operators
Basic arithmetic and logical operators
Assignment operator = Arithmetic operators +-*/%** Logical operators && || ! and or not Increment and decrement operators ++ -Comparison operators == != < <= > >= <=> eq ne lt le gt ge cmp
31
2/22/2012
Conditional Statements
Conditional Statements
Simple If If else Nested If else else if ladder unless
33
2/22/2012
34
2/22/2012
35
2/22/2012
{
if (EXPRESSION) { Statements; } else { Statements; } } else { Statements; }
36
2/22/2012
{
Statements; } elsif (EXPRESSION) { Statements; } elsif (EXPRESSION) { Statements; } else { Statements; }
37
2/22/2012
38
2/22/2012
39
2/22/2012
Loops
Loops
While Loop while (<EXPRESSION>) { Statements; } While loop executes as long as the expression is true and once the expression is false, control exits the loop
41
2/22/2012
Loops (contd..)
Do While Loop do{ Statements; } while (expression); do- while loop executes as long as the expression is true and once the expression is false, control exits the loop. Unlike while loop, do-while loop is executed at least once irrespective of the truthness or falsity of the expression.
42
2/22/2012
Loops ( contd..)
Until Loop until (EXPRESSION) { Statements; } until loop executes as long as the value of the expression is false and exits the loop when the value becomes true.
43
2/22/2012
Loops (contd..)
For Loop Perl's for control structure is like the common for control structure you may have seen in other languages such as C. It looks like this: for (initialization; check; increment) { body; }
44
2/22/2012
Loops (contd..)
foreach Loop foreach loop is same as for loop but does not require initialization and increment as part of the declaration of the loop. @array=(1,2,3,4); foreach(@array) { print This is element $_\n; }
45
2/22/2012
Loop controls
Loop controls
The last Operator The last operator immediately ends the execution of the loop. (If you've used the "break" operator in C or a similar language, it's like that.) It's the "emergency exit" for loop blocks. Example: for ($i=0;$i<10;$i++) { print $i\n; last if ($i == 5); # the loop will exit here }
47
2/22/2012
#This will not print the value of $i and will go #next value in the loop 6
48
2/22/2012
49
2/22/2012
Subroutines
Subroutines
Defining a subroutine use the keyword sub, followed by the name of your subroutine, followed by a code block sub Hello { print Hello and Welcome to this world of Perl\n; }
51
2/22/2012
Subroutines (contd..)
Passing arguments to subroutines When arguments are passed to a subroutine they are stored in the default variable @_.
Getting the arguments directly from the @_ array sub Add { return $_[0] + $_[1]; } Saving the arguments list into another set of variables or another array sub Add { my ($num1,$num2)=@_; return $num1+$num2; }
52 2/22/2012
Confidential McAfee Internal Use Only
Subroutines (contd..)
Using the Shift operator to get the arguments. sub Add { my $num1=shift; my $num2=shift; return $num1+$num2; }
53
2/22/2012
Subroutines (contd..)
Passing Lists to Subroutines. Because the @_ variable is an array, it can be used to supply lists to a Subroutine. All three of the following are valid: @args = (2,3); mysub(1,@args); @args = (1,2,3); mysub(@args); More than one list cannot be passed to a subroutine without using References.
54
2/22/2012
Subroutines (contd..)
The fundamental rule to remember is that when passing arrays or lists to subroutines you can pass only one array or list, and it must be the last argument supplied. sub process { my ($first, $second, @rest) = @_; } If you try to extract the array as the first element, then it will immediately gobble up all of @_, even if there are arguments after the array leaving any scalar entries empty. sub process { my (@rest, $first, $second) = @_; }
55
2/22/2012
Subroutines (contd..)
Passing Hashes to Subroutines
When you supply a hash to a subroutine, the hash is automatically translated into a list of key/value pairs
For E.g. sub display_hash { my (%hash) = @_; foreach (keys %hash) { print "$_ => $hash{$_}\n"; } }
56
2/22/2012
Subroutines (contd..)
The fundamental rule to remember is that when passing hashes to subroutines you can pass only one, and it must be the last argument supplied. This will not work. sub display { my (%hash, $regex) = @_; }
57
2/22/2012
Subroutines (contd..)
Return Values
The return value of any block, including those used in subroutines, is taken as the value of the last evaluated expression. For example:
sub myfunc {
$_[0]+$_[1]; } The return value here is the result of the calculation. You can also explicitly return a value using the return keyword:
sub myfunc {
my $c=$_[0]+$_[1]; return $c; }
58
2/22/2012
Subroutines (contd..)
Return Context In order to discover the context in which a function has been called, you use the wantarray function. For E.g. sub hw { if (wantarray) { return('Hello','World',"\n"); } else { return "Hello World\n"; } }
59
2/22/2012
Subroutines (contd..)
Prototypes
A prototype definition is a parenthesized list of characters mirroring the Perl variable type syntax (that is, $, @, %, and so on). It is placed after the sub keyword and subroutine name but before anything else, be it a subroutine definition, declaration, or anonymous subroutine: sub mysub (PROTOTYPE); # subroutine declaratio sub mysub (PROTOTYPE) {...} # subroutine definition $subref = sub (PROTOTYPE) {...} # anonymous subroutine
60
2/22/2012
Subroutines (contd..)
Prototypes can decide the parameter sequence. If the function has to receive a certain type of parameter as the first one then in the prototype definition it must be prefixed with a \ (backslash)
E.g. sub Add(\@$$); indicates that the first argument must be an array or list followed by two scalars.
61
2/22/2012
Subroutines (contd..)
Prototypes can decide the mandatory and optional parameters. Mandatory and optional parameters are separated by a ; (semicolon) E.g. sub CircleArea($;$) This indicates that the function takes in two parameters, out of which one is mandatory
62
2/22/2012
Perl Modules
64
2/22/2012
65
2/22/2012
66
2/22/2012
68
2/22/2012
69
2/22/2012
Open a File in both Read and Write Mode: To open a file for both reading and writing prefix the > or < with a + sign. open(FH,+< Data.txt);
70
2/22/2012
71
2/22/2012
72
2/22/2012
73
2/22/2012
Open(FH,> Data.txt); Select(FH); $|=1; Print FH This is a test for autoflush enabled\n; Alternaively the module IO::Handle can be used for this, use IO::Handle; open(DOOR,"<file.in") or die "Couldn't open file"; autoflush DOOR 1; To switch it back on again: autoflush DOOR 0;
74
2/22/2012
Open(FH,Data.txt) or die $!; This will exit the program if the file cannot be opened. The system error message is stored in $!. The user can also defined his own custom message when the error occurs. Open(FH,Data.txt) or die File Failed to open. Error $!;
75
2/22/2012
76
2/22/2012
77
2/22/2012
Description
Is it a File? Is it a text file? Is the file executable? Is the file a directory? Does the file exist? Returns the size of the file, with zero referring to an empty file. Is the file size zero?
78
2/22/2012
Regular Expressions
Regular Expressions
The regular expression, also called regex or regexp, is a syntax for expressing search patterns for finding and extracting matches within text. Regexps have a long history, and Perl s implementation. A key to writing good regular expressions is to understand the guiding principles of how the engine seeks a match. Perl s regular expression engine works on three basic principles, in this order: Eagerness: It will try to match as soon as possible. Greediness: It will try to match as much as possible. Relentlessness: It will try every possible combination before giving up.
80
2/22/2012
Transliteration (tr///)
81
2/22/2012
82
2/22/2012
Description
Makes the match case insensitive Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary Evaluates the expression only once Allows use of . to match a newline character Allows you to use white space in the expression for clarity Globally finds all matches
o s x g
83
2/22/2012
84
2/22/2012
85
2/22/2012
86
2/22/2012
87
2/22/2012
88
2/22/2012
90
2/22/2012
92
2/22/2012
93
2/22/2012
94
2/22/2012
95
2/22/2012
8. eof
eof FILEHANDLE eof() eof Returns true if the next read on the specified FILEHANDLE will return an end-of-file condition, or if FILEHANDLE is not currently associated with an open file. If FILEHANDLE is not specified, it returns the condition for the last accessed file. In Scalar Context: undef if FILEHANDLE is not at end of file 1 if FILEHANDLE will report end of file on next read.
96
2/22/2012
97
2/22/2012
98
2/22/2012
99
2/22/2012
100
2/22/2012
101
2/22/2012
102
2/22/2012
103
2/22/2012
104
2/22/2012
105
2/22/2012
106
2/22/2012
107
2/22/2012
108
2/22/2012
Thank You!!