Perl Session
-
Upload
balu-phaneedra -
Category
Documents
-
view
220 -
download
1
Transcript of Perl Session
-
7/28/2019 Perl Session
1/62
Practical Extraction and Report Language
or
Pathologically Eclectic Rubbish Lister
-
7/28/2019 Perl Session
2/62
Perl topics
Why Perl scripting
Basic Structure of Perl Program First Perl Program An example
Operators
Variables & Scope, Scalar Variables & stdin
Perl List Output Functions
Strings and various string functions
Control Flows, Arrays,Hashes
Functions ( Subroutines)
Regular Expressions & Patter matching. File handling.
Perl special variables
CPAN Expect scripting in perl Perl module example
Perl exercises
-
7/28/2019 Perl Session
3/62
Why Perl
Perl syntactically looks like C Perl Open source
Reg. Expressions are easy to implement
Great Community with support
CPAN provides tens of thousands of open sourced modules. Third party support.
-
7/28/2019 Perl Session
4/62
Basic Structure
Barces resemblances to C or Java
semi-colons separate executable statements
{ } delimit blocks, loops, subroutines
Comments begin with # and extend to end of line
No main() function code executed top-down.
Function arguments are comma-separated
-
7/28/2019 Perl Session
5/62
First Perl Program
#!/usr/bin/perlwprint "Now Iam a PERL programmer \n";
Standard: #!/usr/bin/perl[MUST be first line of the file no comments, no spaces
prior to the shebang]
Change the permissions to the file with chmod.
Chmod 755 example.pl
Execution : ./example.pl
-
7/28/2019 Perl Session
6/62
Perl has a range of operators, many of which are similar to the
operators used in C
Assignment Operator
= $n=22; $n2=$n;
Auto increment and decrements operators
++, --
$a++;$b--;
Arithematic operators
+, -, *, /, ** $test = 10 *20 +67 -45
Concatenation Operator
. $test1 = How;$test2=are;$test3=you;
Print $test1.test2.$test3
Operators
-
7/28/2019 Perl Session
7/62
Repetition Operator
X
Print Hay x 9
Relational Operators
Numerical data operators : =, ==, !=, String data operators :
lt gt le ge eq ne cmp(returns -1, 0 , 1)
logical Operators
AND - && or and
OR - || or or NOT - not
Range Operator
..
Print 250..300
-
7/28/2019 Perl Session
8/62
Binding Operator
=~, !~ Used in pattern matching
If ($a =~ m/there/) { print $a; }
Arrow operator
-> Also called reference operator, Used to create objects.
File I/O Operator
Used to read data from files or from standard input.
-
7/28/2019 Perl Session
9/62
Perl variables
Three types of variables
Scalars Defined by $ symbol, used to store either a number or a string
Arrays
Defined by @ symbol, internally List of scalar variables
Hashes Defined by % symbol and each item is identified by a key
value
Variable names are case sensitive Variable name can have alphabets, numbers and underscore (_)
All normal variable rules applicable as in C language Ex : $a=20; $fresh_value=50.58;
-
7/28/2019 Perl Session
10/62
Variables can be scoped either local or global
Global variables can be imported from/exported to other modules
Local variables are restricted to the blocks they are declared in
Variables define with my
The variables declared with my() are visible only within the scope ofthe block which names them. They are not visible outside of thisblock, not even in routines or blocks that it calls. If more than onevalue is listed, the list must be placed in parentheses.
Variables defined with local
'Local' variables, are visible to routines that are called from the
block where they are declared
Scope of variables
-
7/28/2019 Perl Session
11/62
Example on variables scope
my $y=2;
local $x=10;first();print "The value of local variable $x";
sub first {
local $x = 1;my $y = 1;
second(); }sub second {
print "x=", $x, "\n";
print "y=", $y, "\n"; }Output :
x=1
y= 2
The value of local variable 10
-
7/28/2019 Perl Session
12/62
Scalar Variables
A Scalar variable contains a single value. All scalar variables arepreceded by $ Symbol.
All of the standard types from C can be stored in a scalar variable
int, float, char, double, etc
No declaration of type of variable These scalar variables stores either a number or string.
Pre declaration is not required. If used strict module, pre declarationis required.
Example
$Hello = Hi How are you; $pvalue=7.568;
$ivalue=19;
-
7/28/2019 Perl Session
13/62
Reading data from keyboard as input
or is input operator, used to read data from keyboardincluding \n (From user)
Perl special variable $_ (@_) will stores this input value.
Example:#!/usr/bin/perl
print Enter your name ;
$name = ;
print \n Hi $name how are you;
STDIN
-
7/28/2019 Perl Session
14/62
Lists
A list is a comma-separated sequence of scalar values.
Collection of scalar data, Arrays and Hashes Represents a logical group of items
Any number, and any types of scalars can be held in a list:
(42, krishna kumar', sample,75.5); Lists are passed to functions, stored in arrays, and used in assignments my ($foo, $bar, $baz) = (35, 43.4, 'hello');
An assignment of a list of variables need not containthe same number of values on the left and right:
my ($foo,$bar)=(34,'hello',98.3);
98.3 simply discarded my ($alpha, $beta) = 5;
$alpha gets 5, $beta remains undefined
-
7/28/2019 Perl Session
15/62
List assignments can be used to 'swap' variables:
my ($one, $two) = ('alpha', 'beta'); ($one, $two) = ($two, $one);
Example
print (1,2,3) displays 123
-
7/28/2019 Perl Session
16/62
Output functions
Perl has print and printf functions.
print Is Unformatted output statement which can print a string, Number or
a List
Default outputs to STDOUT, can be redirected to STDERR or a File
print $myvalue; print FP I am going to print in File;
printf
Formatted output statement
By defaults outputs to STDOUT. Can be redirected to STDERR or aFile printf Format, variable list printf FP, variable List
-
7/28/2019 Perl Session
17/62
Perl strings
String is the Sequence of characters. Perl strings are two types Single quoted string
Variable values are not interpolated.
Example : $a = 10; print \n The value of a is $a; o/p : \n The value of a is $a
Double quoted string Variable values are interpolated
Example : $a = 10; print The value of a is $a;
o/p : The value of a is 10
-
7/28/2019 Perl Session
18/62
String operators
Concatenation & repetition Operator can be applied
on strings
Some String functions lc STRING Used to convert to lower case uc STRING Used to convert to Upper case
lcfirst STRING Used to convert initial case to lower
ucfirst STRING Used to convert initial case to upper
length (STRING) Used to get length of string
substr STRING,OFFSET,[LENGTH], REPLACEMENT
Used to extract/replace substring from main string
-
7/28/2019 Perl Session
19/62
Perl control structures
Blocks
Branching Statements if
if else
if elsif
Looping Statements while / until
do while/ until
for
foreach
Other Control Statements last, next, redo
exit, die
-
7/28/2019 Perl Session
20/62
Blocks
Blocks are set of statements enclosed between pair of
curling braces and each statement is delimited withsemicolon (;)
Example :
{
an expression;
another expression;
another expression;
last one;}
-
7/28/2019 Perl Session
21/62
If - block
if (expression) {
an expression;
another expression;
last one
}
If else - block
if (expression) {
an expression;
another expression;
last one
} else {
}
Branching statements
-
7/28/2019 Perl Session
22/62
If-elsif block
if (expression) {
an expression;
another expression;
last one} elsif (expression) {
}
-
7/28/2019 Perl Session
23/62
while loopwhile (condition) {
#while block statements
}
Control comes out of the loop when the condition is FALSE
until loopuntil (condition) {
#until block statements
}Control comes out of the loop when the condition is TRUE
Looping statements
-
7/28/2019 Perl Session
24/62
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
-
7/28/2019 Perl Session
25/62
for
for(init expr ; condition ; increment/decrement ) {
#for block
}
foreachmostly used when iteration has to be done for different values in a list
foreach Variable (LIST) {
#Block of Statements
}
-
7/28/2019 Perl Session
26/62
Other Control statements
last
exits the loop
continue block is not executed, if present
Will not evaluate the value of the control variable but repeats theloop
continue flow control statement follows while or foreach loop
continue block will be executed after every successful completion ofan 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
-
7/28/2019 Perl Session
27/62
exit
used to terminate the execution of a script
exit 0 denotes success and exit 1 denotes failure
cannot display error messages while exiting
$Choice= 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
-
7/28/2019 Perl Session
28/62
Arrays
Arrays are variables that contain a list.
Arrays are declared with any size or type. They can hold lists containing anynumber or type of values.
Size can grow/shrink dynamically.
All array variable names begin with @
my (@s, @stuff, $size); @s =('a', 'list', 'of', 'strings');
@stuff = (32, 'Paul', 54.09);
-
7/28/2019 Perl Session
29/62
Accessing array elements
To get at a specific element of the array, place the index number in []after the array name, and replace the @ with a $ You're accessing a*single* value
my @foo = ("Hello", "World");my $greeting = $foo[0];
my $location = $foo[1]; my @age =('I am', 25, 'years old');
$age[1] = 26;@age now => ('I am', 26, 'years old')
-
7/28/2019 Perl Session
30/62
Array flattening
Remember that lists (and therefore arrays) can only contain scalar values.
Trying to place one array in another will result in array flattening:
my @in = (25, 50, 75);
my @out= ('a', 'b', 'c', @in, 'd', 'e');
@out contains eight elements:
a, b, c, 25, 50, 75, d, e Arrays on LHS of assignment will 'eat' remaining elements:
my ($foo, @bar, $baz) = (5, 6, 7, 8);
$foo = 5, @bar = (6, 7, 8), $baz undefined
-
7/28/2019 Perl Session
31/62
Special array variable
for any array @foo, there exists a scalar variable $#foo, which containsthe last index of @foo
@stuff = (5, 18, 23, 10);
$#stuff 3
This variable can be used to dynamically alter the size of the array:
$#stuff = 10; #@stuff now has 7 undef's$#stuff = 1; #@stuff now => (5, 18)
To receive the length of the array
$length = @array
To receive the first element of the array
($first)=@array
-
7/28/2019 Perl Session
32/62
Some Functions supported on Arrays
To copy one array to a new array
@array1 = @array2 To add an new value to beginning of the array
unshift(@array, newelement);
To add the value to the end of the array
push( @array, newelement); To remove first value of an array
shift(@array)
To remove the last element of the array
pop(@array)
To replace the specific element in an array $array[number]=$newelement;
To sort any array sort(@array)
-
7/28/2019 Perl Session
33/62
To reverse the elements in the array
reverse( @array)
Delete or replace elements with in the array can be made using splicefunction
splice(arrayname,position,numberof elements) If user wants to make a string from array elements with some delimiter
join function will be useful.
join (delimeter, arrayname)
The split function will be useful when user wants to create an array fromstring with constant delimeter
@browser=split(/delimeter/, $list)
-
7/28/2019 Perl Session
34/62
Hashes
Also known as associative arrays
Hash names start with a % A list of key/value pairs.
Unordered collection of values
Each element is linked to a key, which uniquely identifies that element.
Writing the value of a hash at an existing key overwrites the existingvalue.
Similar to arrays, but 'indices' can be any scalar value, not just integers.
both the keys and values can be any scalar value, including multipletypes in the same hash.
Any element from the hash can be retrieved, added, deleted using thekey
Used to maintain a list of corresponding values.
-
7/28/2019 Perl Session
35/62
Hash Example
Creating an empty Hash
%new_hash=();
Creating hash with elements
my %points_for = ('touchdown' => 6,'point after' => 1,'safety' => 2,'field goal' => 3
);
or
my %new_hash= (cpu' , intel',
printer' , cannon',
keyboard' , dell'
);
-
7/28/2019 Perl Session
36/62
Similar to arrays, access specific element by replacing % with $, andenclosing the key in { }
Accessing elements
Elements can be retrieved using key
$RetrievedElement = $Hash{Key};
Displaying hash elements
% new_hash= (
cpu' , intel',
printer' , cannon',
keyboard' , dell
)
print $new_hash{cpu};
print $new_hash{keyboard};
print %new_hash;
-
7/28/2019 Perl Session
37/62
Tip: If you feel the need to keep two lists of values, and accesscorresponding values in each list you want a hash.
Adding new elements
$Hash{ new key}= new element
Changing the existing elements
$Hash{key} = new element
Example
my %n=('two'=>'beta', 'one'=>'alpha');
if key is single word, can omit the quotes:
$n{two} = 2; #%n still has only 2 key/value pairs
$n{last} = 'omega';#%n now has 3 key/value pairs
-
7/28/2019 Perl Session
38/62
Deleting an element from Hash
delete ($Hash{$Key}) Reversing Hash
reverse (%Hash)
reverses keys and values
after reversal keys become values and vice versa Merging two Hashes
%NewHash = (%Hash1,%Hash2);
Using keys all keys of Hash can be retrieved
my %n=('two'=>'beta', 'one'=>'alpha');
@keyarray = keys (%n); Using values all key values of Hash can be retrieved
my %n=('two'=>'beta', 'one'=>'alpha');
@valuesarray = values (%n);
-
7/28/2019 Perl Session
39/62
Hashes will "flatten" if assigned to an array:
my %prof_of = (Perl => 'Lalli',CS1 => 'Hardwick',CS2 => 'Cutler');
my @profs_and_classes = %prof_of;
@profs_and_classes('CS1', 'Hardwick', 'CS2', 'Cutler', 'Perl', 'Lalli')
-
7/28/2019 Perl Session
40/62
Subroutines
Portion of the script that performs a specific task. Common repeatedtasks can be put under subroutine.
Function/subroutine same thing in perl Pre declaration not essential
If user needs to pre declare use the keyword sub
Example : sub ADD Any arguments passed to the subroutine are show up in the array @_.
Therefore, if you called a function with two arguments, those would bestored in $_[0] and $_[1].
The return value of a subroutine is the value of the last expressionevaluated. More explicitly, a return statement may be used to exit thesubroutine
-
7/28/2019 Perl Session
41/62
Sample examples
Example:
sub mySub{
print Oh!!! its really executed \n;
}
# Function call&hello;
-
7/28/2019 Perl Session
42/62
Arguments
Arguments passed as single list - the argument array @_
Example :&fun2(1, abc);
sub fun2{
print a1=$_[0], a2=$_[1]\n;
}
So Common technique to name arguments:Example:
sub another{
my($a, $b, $c) = @_;
# ...}
$a, $b, $c set to first 3 values of @_
-
7/28/2019 Perl Session
43/62
Regular expressions
A regular expression, often called a pattern in Perl, is atemplate that either matches or doesn't match a given string. Incredibly powerful feature of Perl Uses Match operator (=~ or !~ ) The =~ operator tests whether pattern is matched. !~ is similar to =~ operator, expect that it checks whether a
patter is not matched.
-
7/28/2019 Perl Session
44/62
^ Matches the beginning of input.
$ Matches the end of input. * Matches the preceding character zero or more times. For example,
"zo*" matches either "z" or "zoo".
+ Matches the preceding character one or more times. For example,
"zo+" matches "zoo" but not "z". ? Matches the preceding character zero or one time. For example,
"a?ve?" matches the "ve" in "never".
.Matches any single character except a newline character.
{n}n is a nonnegative integer. Matches exactly n times. For example,"o{2}" does not match the "o" in "Fob," but matches the first two o's in"foooood".{n,}n is a nonnegative integer. Matches at least n times.
For example, "o{2,}" does not match the "o" in "Fob" and matches allthe o's in "foooood". "o{1,}" is equivalent to "o+". "o{0,}" is equivalentto "o*".
-
7/28/2019 Perl Session
45/62
{n,m}m and n are nonnegative integers. Matches at least n and at mostm times. For example, "o{1,3}" matches the first three o's in "fooooood"."o{0,1}" is equivalent to "o?".
[xyz] A character set. Matches any one of the enclosed characters. Forexample, "[abc]" matches the "a" in "plain".
[ xyz] A negative character set. Matches any character not enclosed.For example, "[^abc]" matches the "p" in "plain".
\d Matches a digit character. Equivalent to [0-9].
\D Matches a non digit character. Equivalent to [^0-9].
\fMatches a form-feed character.
\n Matches a new line character.
\rMatches a carriage return character.
-
7/28/2019 Perl Session
46/62
\s Matches any white space including space, tab, form-feed, etc.Equivalent to "[ \f\n\r\t\v]".
\S Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".
\t Matches a tab character.
\v Matches a vertical tab character. \w Matches any word character including underscore. Equivalent to
"[A-Za-z0-9_]".
\W Matches any non word character. Equivalent to "[^A-Za-z0-9_]".
-
7/28/2019 Perl Session
47/62
Sequence /foo/ # matches foo
Alternation /foo|bar/ # matches foo or bar; same as
/(foo)|(bar)/ Multipliers
/\d+/ # match a non-empty string of digits /(\+|\-)?\d+/ # match a signed integer /\s*/ # zero or more white-space characters /{\d}4\-{\d}2\-{\d}2/ # match the date format yyyy-
mm-dd
For more http://www.cs.tut.fi/~jkorpela/perl/regexp.html
-
7/28/2019 Perl Session
48/62
Example 1
$_ = 2006-09-25";If (/(\d\d\d\d)\-\d\d-(\d\d)/) {
$year = $1;
$day = $2;
}($year, $day) = /(\d\d\d\d)\-\d\d-(\d\d)/;
Example 2
$_ = "number_of_lines";
s/number_of_lines/numberOfLines/;
while () {next if /^\s*#/; # skip comment lines
s/^\s+//; # remove leading white space
s/\s+$//; # remove trailing white space}
-
7/28/2019 Perl Session
49/62
File Handling
Data that flow from the the program
needs to be stored in a permanent storage so that it can bereferred to later
In PERL files are given a name, a handle, basically another way ofsaying alias. All input and output with files is achieved throughfilehandling. Filehandles are also a means by one program maycommunicate with another program
A filehandle is nothing more than a nickname for the files
The die function exists with the help of this function we can shoot outerrors while handling files
Files are opened with open function and close with close function
Opening a File
open FILEHANDLE, FileName
-
7/28/2019 Perl Session
50/62
Data.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 (FP,>>Data.txt)
Different file opening modes
-
7/28/2019 Perl Session
51/62
+>
+> will erase the existing contents and open the file for readand write
open (FP, +>Data.txt)
+