Sie sind auf Seite 1von 53

PERL TRAINING

SWAROOP KULKARNI
swaroopk@tataelxsi.co.in
H & S GROUP
Day 1 Schedule

Session 1 (11.00-12.45) Introduction


Data types
Session 2 (1.45-3.15) Lab1

Session 3 (3.30-5.30) Associative arrays


File handling
Day 2 Schedule

Session 1 (9.30-11.30) Pattern Matching

Session 2 (11.45-12.45) Lab2

Session 3 (1.45-3.15) Subroutines

Session 4 (3.30-5.30) Lab3


Introduction to Perl

•Perl is an Acronym for


Practical Extraction and Report Language

•Perl was designed by Larry Wall in the year 1986

•Features of Perl

power and flexibility of a high-level programming


language such as C
Like shell script languages, Perl does not require a special
compiler and linker to run

• Interpreted Language
Interpreted Vs Compiled
Interpreted Language
• Code you enter is saved in the same format.
• Executed immediately after parsing - performed by the interpreter
• Relative ease of programming and no linker is required
• Disadvantages include poor speed performance and that you do not
generate an executable
• Ex : Perl,Java,Basic
Compiled Language
• Compilers parse the instructions into machine code and store them in a
separate file
• Compiled programs generally run faster
• Ex: C, C++, VB
Course Requisites and Goals

• This course presumes participants have elementary


programming experience in a procedural programming
language such as C.

• By completing this course, you should be able to:


o Express fundamental programming constructs such as

variables, arrays, loops, subroutines and input/output in


Perl
o Understand several concepts such as associative arrays,

Perl regular expressions


Simple Perl Program
On a Unix system, write a text file named e.g. myprog.pl.

Indicates location of Perl


#!/usr/bin/perl Interpreter on local machine
#
print "Hello!\n"; “\n” represents a new line (line
feed) character
Then make this file executable for you
% chmod +x myprog.pl
and call it like any Unix command:
% myprog.pl or perl myprog.pl
Alternatively, Perl commands can also be submitted directly from the UNIX
command line:
% perl -e 'print "hello!\n"'
Introduction to Perl

• Command line options


-c syntax check only, not execute
-d Run script using Perl debugger
-e Pass a command to Perl from command line
-v Print Perl version number
-w Print warning about Perl syntax
Basics of Perl
• Lines starting with # are ignored , except the line
starting with #!, which indicates the path to the Perl
interpreter on the system.
• Individual commands are separated by ;
• Variable names start with a $
• Blocks of commands are encompassed by {…}

Example of a Perl script which computes and prints the square-


roots of integers 1 to 20.
#!/usr/bin/perl
#
for($i=1; $i <= 10; $i = $i+1) {
$sqrt = $i**0.5;
print "square-root of $i is $sqrt\n"
}
Building blocks of perl
 Data types
– scalar - stores exactly one item, a line of text or number.
– Arrays - collection of scalar
• @myArray = (“adf”, 233,$my_var);
• Array subscripts are denoted by bracket.
• $myArray[0] refers to first element in the array ie.,
“adf”
– Associative Arrays - lists of values indexed by strings
• %mylangArray = (“perl”, 5, “vb”, 6);
• $mylangArray{“perl”} - refers to 5
 File handles - Pointer to a file from which Perl is to read or
write.
 Pre-defined file handles are STDIN, STDOUT, STDERR
Scalar Variables

• Stores exactly one item-a line of text or number


• Preceded by a $
• Integer scalar value (+ or -)
• Floating point scalar value
Ex: 3 . 2 , 4 e 2
• Octal and hex value
Ex: $var = o47; $var = 0x1f ;
• Strings
Ex1: $my_var = “This is text”;
Ex2: $my_var1 = 2; $my_var2 = “This is $my_var1”;
Scalar Variables

• Single quoted strings allowed


Ex1 : $my_var = ‘this is a text’;
Ex2 : $my_var1 = 2; $my_var2 = ‘this is $my_var1’;
• Numeric value allowed as string
Ex1 : $my_var = 2 + “20”; (Result: my_var contains 22)
Ex2 : $my_var = 2 + “text”; (Result:my_var=> 2 + 0 => 2)
• Initial value of a scalar variable is null
Escape Sequences

\a Bell (beep)
\n Newline
\t Tab
\u Force next letter to uppercase
\l Force next letter to lowercase
\U Following entire string to UC.
\L Following entire string to LC.

Ex: print “Hello world \n”;


Perl Operators
• Logical Operators
– AND &&
– OR ||
• Arithmetic Operator
– Multiplication *
– Division /
– Addition +
– Subtraction -
– Exponentional **
– Remainder %
– Unary -
Perl Operators
Comparison Operators
String operator Comparison operation Equivalent
numeric operator
lt Less than <
gt Greater than >
eq Equal to ==
le Less than or equal to <=
ge Greater than or equal to >=
ne Not equal to !=
cmp Compare, return 1, 0, or -1 <=>
Perl Operators

Bit Manipulation Operator


The & (bitwise AND) operator
The | (bitwise OR) operator
The ^ (bitwise XOR or "exclusive or") operator
The ~ (bitwise NOT) operator
The << (left shift) and >> (right shift) operators
Perl Operators
Assignment Operator
= Assignment only
+= Addition and assignment
-= Subtraction and assignment
*= Multiplication and assignment Ex: $a *= $b
/= Division and assignment => $a = $a * $b;
%= Remainder and assignment
**= Exponentiation and assignment
&= Bitwise AND and assignment
|= Bitwise OR and assignment
^= Bitwise XOR and assignment
Perl Operators

String Operators
. Concatenates two strings $var = $var1.$var2;
x Repeates a string $var = $var1 x 3;
.= Concatenates and assigns $var .= $var1;

Other Perl Operators


Comma Operator ,
Ex : $my_var1+=1 , $my_var2 = $my_var1;
Conditional Operator ? :
Ex : $my_var = 0?14:7 ;
Perl Statements
if..elsif..else
unless
while
do
until
for
foreach
Labels (next, last)

#!/usr/bin/perl
for($i=1; $i <= 10; $i = $i+1) {
$sqrt = $i**0.5;
print "square-root of $i is $sqrt\n"
}
Perl Statements

• unless (expression) { } ||| if (! expression) { }

• While / until Structure


while (expression) until (expression)
{ {
} }
Enters if expression = 1 Enters if expression = 0
• for ($i=1; $i <= 10; $i = $i+1) {
$sqrt = $i**0.5;
print "square-root of $i is $sqrt\n"
}
Perl Statements

• Foreach Statement
foreach $my_var (@my_arr)
{ next if $my_var = 10;
print “$my_var \n”;
last if $my_var = 5;
}

• Next is similar to continue in C.


• Last is similar to break in C.
Lists and Arrays

 List – Collection of scalars


(“my_string”, 24.3, 2, $my_var1+$my_var2)
 Array – Variable to store a list
Preceded by an @
@my_array = (“my_string”, 24.3, 2, $my_var1+$my_var2)
 Accessing Array Variables
$var = $my_array[0];
$my_array [0] = “my_string” , $my_array [1] = 24.3

 Array length
$my_var = @my_array - gives the length of the array
($my_var) = @my_array – assigns the first value of
the array
Lists and Arrays

 Array slicing
@my_slice = @my_array [1,2,4];

 List Range Operator


(1..5) - yields (1,2,3,4,5)
(2.1..4.3) – yields (2.1,3.1,4.1,4.3)

 Reading from STDIN into an array


@my_array = <STDIN>;
Arrays and Library functions
Function Definition
push(@my_array, Element) Adds to the end of an array
pop(@my_array) Removes the last element of
the array
unshift(@my_array, Element) Adds to the beginning of an
array
shift(@my_array) Removes the first element of an
array
delete $my_array[index] Removes an element by index
number
Arrays and Library functions
 Sort - sorts the array in alphabetical order and returns
@my_retlist = sort(@my_array);

 Reverse – reverses the array and returns


@my_retlist = reverse(@my_array);

 Chop – deletes the last character in the array


@my_list = (“rat”,1,3, “king”);
chop(@my_list) = (“rat”,1,3, “kin”)
Arrays and Library functions

 Join – joins the elements of an array into one variable


Ex: @my_array = (“this”, “is”, “a”, “string”);
$my_string = join(‘ ’,@array);
(Result: $my_string = “this is a string”)

 Split – Splits the variable into an array based on a pattern

Ex: $my_string = “This is a line”;


@my_array = split (/ /,$my_string);#Space is a pattern here
(Result: @my_array = (“This”, “is”, “a”, “line”) )
Associative Arrays

 Associative Arrays (Hashes)


A regular array uses whole numbers for indices, but the
indices of a hash are always strings.
Use the % when referring to the hash as a whole.
A hash can be initialized with a list, where elements of the
list are key and value pairs:
%age = ( “Amar” , 24, “Akbar”, 25, “Anthony”, 26 );
No matter what order you insert your data, it will come out
in an unpredictable disorder
Associative Arrays

• Accessing elements of array variables


$my_hash{$key}
• Adding elements
$fruit {“bananas”} = 1;
• Deleting elements
delete($fruit{“orange”});

print "an example for using the Associative Array \n\n";


%myhash = ("first", "1", "second", "2" , "third", "3");
print $myhash{"first"};
Associative Arrays

• Array Indexes, key-value pair


$my_hash{$my_key} = $my_value;

foreach $key (keys %my_hash)


{ $value = $my_hash{$key};
# do something with $key and $value }
(Note: keys is a keyword)
File Handling in Perl

• Open function-The open function opens a file for input


open(my_handle, “file_name”); # Open the file

• File Access function


read, write, append
open(my_handle, “file_name”); # Open for input
open(my_handle, “>file_name”); # Open for output
open(my_handle, “>>file_name”); # Open for
appending
File Handling in Perl

 Writing to a File
print my_handle "This line goes to the file.\n";

 Reading in to an Array Variable


@lines = <my_handle>;

 close function
close(my_handle);
File Handling in Perl
 File test operators
-d Is name a Directory?
-e Does name exists?
-r Is name a readable file?
-s Is name a non-empty file? Returns size of file.
-w Is name a writable file?
-x Is name an executable file?
-z Is name an empty file?
Ex: if (!(-e “file1”))
print(“File doesnot exists”);
File Handling in Perl

Directory manipulation functions


mkdir,opendir,readdir,closedir

File Permission Functions


chmod, chown

File rename
rename(“file1”, “file2”)
Example for Reading File with Error handling

unless (open(INFILE, "infile")) {


die ("Input file infile cannot be opened.\n");
}
if (-e "outfile") {
die ("Output file outfile already exists.\n");
}
unless (open(OUTFILE, ">outfile")) {
die ("Output file outfile cannot be opened.\n"); }

$line = <INFILE>;
while ($line ne "") {
chop ($line);
print OUTFILE ("\U$line\E\n");
$line = <INFILE>;
}
Pattern Matching
• Regular Expression is a pattern that the string is matched
for.
• Match Operators
=~ !~
Ex : $sentence =~ /the/ $line !~ /the/
Program:
open(IN_FILE, "alice.txt");
@lines = <IN_FILE> ;
close(IN_FILE);
# searching the file content line by line:
foreach $line (@lines){
if ($line =~/the/){
print $line;
} # end of if
} # end of foreach
Pattern Matching

• Special characters
. Any single character except a newline /t.e/
^ The beginning of the line or string /^a/
$ The end of the line or string /n$/
* Zero or more of the last character /^a.*n$/
+ One or more of the last character /to+/
? Zero or one of the last character /to?/
Pattern Matching
 Special Characters [ ]
[qjk] Either q or j or k
[^qjk] Neither q nor j nor k
[a-z] Anything from a to z inclusive
[^a-z] No lower case letters
[a-zA-Z] Any letter
[a-z]+ Any non-zero sequence of lower case letters

 Characters like $, |, [, ), \, / and so on are peculiar cases in


regular expressions-preceed it by a backslash.
\[ An open square bracket
\) A closing parenthesis
\* An asterisk
Pattern Matching

 Some more special characters:


\n A newline
\t A tab
\w Any alphanumeric character, same as [a-zA-Z0-9]
\W Any non-word character, the same as [^a-zA-Z0-9]
\d Any digit, the same as [0-9]
\D Any non-digit, the same as [^0-9]
\s Any white space character: space, tab, newline, etc
\S Any non-white space character
\b A word boundary
\B No word boundary

Ex: /\bt\we\b/
Examples

• Retrieve lines that have a word of any length that


starts with t and ends with e.
/\bt\w*e\b/
• a word that starts with an upper case letter
/\b[A-Z]/
• the word "yes" in any combination of upper and
lower case letters
/\b[Yy][Ee][Ss]\b/ or /\byes\b/i
Pattern Matching

• The $_ Special variable

if ($sentence =~ /under/) if (/under/) {


{ print “$sentence”; } print “$_”;}
Pattern Matching
 Substitution operator
s/pattern/replacement/
 Translation operator
tr/string1/string2/

 Pattern Matching Options


g Match all possible patterns
i Ignore case
o Only evaluate once
x Ignore white space in pattern
Examples

• Replaces every occurrence of Alice by Mary


s/Alice/Mary/
• Print two blank space characters after the "." at the end of a
sentence.
s/\. /. /g;
• Replace single quotes (' or `) by double quotes.
s/[`']/"/g;
Special Variables

 Environment variables
$ENV{env_variable}

 Program Arguments
@ARGV contains the list of command line arguments

 System commands
system(“cd .. ; perl myperl.pl”);
SUBROUTINES

 Sub unit in a Perl Program

 Groups sequence of code

 Can be written anywhere in the program

 Always takes the latest version


SUBROUTINES
The subroutine is called by prefixing the name with
the & character.

sub mySubRoutine {
<do something >
}
# invoke the sub routine
&mySubRoutine;
Example to illustrate the Subroutine
sub fun1()
{ my $a=0;
print "before calling another function the value is : " . ($a);
&fun2($a);
print "\n After calling the second function the value is : " . ($a);
}
sub fun2()
{ my($v)= @_;
$v =12;
print "\n after the my variable is passed & modified : " . s $v;
}
&fun1();
Passing Arguments to Subroutine

 All arguments are treated as one single flat scalar variable.


 Any arrays or hashes in these call and return lists will
collapse, losing their identities.
 All arguments are stored in as array @_. If a function with
two arguments, those would be stored in @_[0] and
@_[1]. The array @_ is a local array, but its elements are
aliases for the actual scalar parameters.
Example:

&max($mon,$tue,$wed,$thu,$fri); # calling the subroutine


sub max
{
my $max = @_ ; // lexical local variable declaration
< do something >
}
Recursive Subroutine

 Subroutine calling themselves as termed as recursion


subroutine.
 Termination from the subroutine should be taken care.
sub factorial {
local($x) = @_;
if ($x == 1)
{ return 1;
}
else
{ return ($x*($x-1) + &factorial($x-1)); }
}
Returning Values
 The return value of the subroutine is the value of the last
expression evaluated.
 A return statement may be used to exit the subroutine.
 Return of more than one arrays and/or hashes, will be
flattened together into one large indistinguishable list.
Example
sub max {
$max = shift(@_);
foreach $foo (@_) {
$max = $foo if $max < $foo; }
return $max; }
$bestday = max($mon,$tue,$wed,$thu,$fri);
Predefined Subroutines
• Perl 5 defines three special subroutines that are executed at
specific times.

• AUTOLOAD subroutine, which is called when your program


can't find a subroutine it is supposed to execute

• BEGIN subroutine - Enables to create code that is executed


when the program is started.

BEGIN {
Print { “ this is first subroutine to be called”};
}
• Multiple BEGIN subroutines can be defined. These
subroutines are called in the order in which they appear in the
program.
Predefined Subroutines

 END subroutine - Enables you to create code to be


executed when your program terminates execution.

END {
Print {“ this is the last statement to be executed” };
}

 Multiple END subroutines in your program. In this case,


the subroutines are executed in reverse order of
appearance, with the last one executed first.
THANK YOU

Das könnte Ihnen auch gefallen