Вы находитесь на странице: 1из 40

PERL

- A quick-and-dirty Language

Somesh Saraf
20-21 Dec 2006
Table of Contents
 Prerequisites

 Perl Script
 First Perl Script

 Data Types

 Flow Control

 Subroutines

 Regular Expressions

 File Handling
Prerequisites
 Perl Interpreter
 ActivePerl- a freely available pre-configured, ready-to-
install package - of Perl on Windows.

 Editor
 Any conventional Text Editor- NotePad, Wordpad, Editplus
etc.

 Running Perl
 perl sample.pl
 /usr/local/hin/perl sample.pl (Unix)
 c:\NTperl\perl sample.pl (Windows)
Perl Script
 Anordinary text file containing a series of Perl
commands.

 Broad syntactic rules


 You can start a Perl statement anywhere you want.
 Commands are terminated with a semicolon.
 Comments start with a pound sign (#) is ignored.
First Perl Script
use strict;
# strict is a pragma which instructs Perl
# interpreter and user to declare each
# variable and function.

my $training = “Perl Session”;


print(“This is first $training!!\n");

" This is first Perl Session!!\n"


Scope of variables
 Defaultglobal scope
 my and local keywords

my index = 0;
local count = 0;
my : variables declared using my can live only within
the block it was defined and but are not visible in
the subroutines called inside the block
local : variables declared using local are also visible
in the subroutines called inside the block.
Data Types
 Small number of data types:
 scalars and arrays

 Associative array : very special kind of array


Data Types - Scalar
 All numbers and strings are scalars.

 Scalar variable names start with a dollar sign.

 Variable names are case sensitive.

Creative Perl
$Num = 10;
$Str = “Perl Session”;
$Session = $Str.$Num;
Data Types
 Numbers
100; # The number 42
100.5; # A Foating point number
100.000; # 100
10E2; # 100

 Strings
Can be of any length
Can contain any characters, numbers, punctuation,
special characters (like `!', `#', and `%'),
Can contain special ascii formatting characters like newline,
tab, and the \bell" character.
String Functions
 length
Returns the length of the string in bytes.

 chomp
Removes line ending characters from a string or array of strings.

 chop
Removes the last character from a string or array of strings.

 lc
Converts all characters in the string to lower case.

 uc
Converts all characters in the string to upper case.

 index
This function returns the position of the first occurance of the specified SEARCH
string. If POSITION is specified, the occurance at or after the position is returned.
The value -1 is returned if the SEARCH string is not found.
String Functions
 substr
 Returns a substring from a string.
 Has 3 variants
substr (STRING,OFFSET)
returns all characters in the string after the designated offset from
the start of the passed string.
substr (STRING,OFFSET,LEN)
returns all characters in the string after the designated offset from
the start of the passed string up to the number of characters
designated by LEN.
subst (STRING,OFFSET,LEN,REPLACEMENT)
replaces the part of the string beginning at OFFSET of the length LEN with
the REPLACEMENT string.
Data Types - Arrays
 A collection of scalars.

 An array variable name starts with an @ sign

 Array Initialization:
@MotoPhones = (“V3i", “Ming", “MotoQ");

 Accessing array elements


$MotoDiv[0], $MotoDiv [1] etc…
Data Types - Arrays
 Array can have mixed scalar types
 @items = (15, 45.67, "case");

 Ifan array is evaluated in scalar context, it


yields the number of elements in the array.
my $word = @params;
print "$word\n";
Data Types – Associative
Arrays
 Hash Table
 Provide Database functionality
 Ordinary Arrays associated with key/value pair

%CR = ( ‘CR1001-1001’, ‘DVR',


‘CR1001-1002’, ‘USB',
‘CR1001-1002’, ‘Gfx' );
print ($ CR {‘CR1001-1001’});
Data Types – Associative
Arrays
 Keys and values may be treated as separate
(ordinary) arrays

print keys %CR;


print values %CR;

Extracting individual keys/values


foreach $var (keys %CR)
{
print "$var: \"$ $CR{$var}\".\n";
}
Operators
 Logical Operators
 || (or) and && (and) operators
$Weekend = $Saturday || $Sunday;
$Solvent = ($income > 3) && ($debts < 10);

Creative Perl
$Weekend = $Saturday or $Sunday;
$Solvent = ($income > 3) and ($debts < 10);
$value > 10 || print "Oops, low value $value ...\n";
$value > 10 && print "OK, value is high enough…\n";
Operators
 Relational Operators
Operator Numeric Context String Context

Equality == eq

Inequality != ne

Inequality with <=> cmp


signedresult

Greater than > gt

Greater than or equal to >= ge

Less than < lt

Less than or equal to <= le


Conditional Expressions
If (<condition>)
perl statement;
else
perl statement;

If($a > 10)


print “Value out of bound\n”;
else
print “Ok to proceed\n”;

Creative Perl

$a = 10;
Print “Value of input is $a\n” if $debug;
Conditional Expressions
 unless :
 The statement does not execute if the logical
expression is True and executes otherwise.
while The statement executes repeatedly until the logical expression is False.

unless($directory eq “vxworks” )
{
perl statement;
….
}
Loops – while
while(<condition>)
{
perl statements;
}
The statement executes repeatedly until the logical expression is True.

my $a = 0;
while ($a < 10)
{
print "a -> $a\n";
$a++;
}

Creative Perl

my $a = 0;

print "a -> $a\n" while $a++ < 10;


Loops- until
until(<condition>)
{
perl statements;
}
The statement executes repeatedly until the logical expression is False.

my $a = 0;
until ($a > 10)
{
print "a -> $a\n";
$a++;
}

Creative Perl

my $a = 0;

print "a -> $a\n" until $a++ > 10;


Loops- for
 The for statement resembles the one in C
followed by an initial value, a termination
condition, and an iteration expression, all
enclosed in parentheses and separated by
semicolons.

for ( $count = 0; $count < 100; $count++ )


{
print "Something";
}
Loops- foreach
 Iteratesover the contents of an array and
executes the statements in a statement block
for each element of the array.

@numbers = ("one", "two", "three", "four");


foreach $num ( @numbers )
{
print "Number $num…\n";
}
Subroutines
 Basic subunit of code in Perl

 Similar to a function in C and a procedure or a


function in Pascal

 May be called with various parameters and returns a


value.

 Groups together a sequence of statements so that


they can be re-used.
Subroutines
 Can be declared anywhere in a program.
 If more than one subroutine with the same name
declared only the last one is effective.

 Declaration
sub subroutine-name { statements }

sub PrintInfo
{
print “This is first perl session\n”;
}
Subroutines
Subroutine call
 By prefixing the name with the & character.

&PrintInfo;
sub PrintInfo
{
print “This is first perl session\n”;
}
Subroutines
 Returning Values from Subroutines

&GetValue; Creative Perl

sub GetValue
(@return-a1, @return-a2) = &egsub4;
{
sub egsub4
return $value\n”; {
local(@a1) = (a, b, c);
} local(@a2) = (d, e, f);
return(@a1,@a2);
}
Subroutines
Passing Values to Subroutines

 The call simply lists the variables to be passed.


&PrintError($Str,$StrLength);

 Parameters are passed in the list @_ to the subroutine.

sub PrintError
{
($ValToPrint,$ValLength) = @_;
print “Value is $ValToPrint of Length ,$ValLength \n”;
}
Subroutines
 Pass by Reference : Directly use @_
sub Increment
{
@_[0]++;
print “Value after increment $_[0]\n”;
}

 Using shift to get parameters Creative Perl


sub PrintError Same holds good for CommandLine
{ Arguments
$ValToPrint= shift;
$ValLength= shift;
print “Value is $ValToPrint of Length ,$ValLength \n”;
}
File Handling
 File Handle
 A pointer to a file from which Perl is to read or to
which it will write.
 Behaves in many ways like a variable

 Opening a file
open (<FILEHANDLE>, “<Mode><FileName>");
open (LOGFILE, ">/etc/logs/reclaim.log");
File Handling
Symbol Meaning
< Opens the file for reading. This is the default action.
> Opens the file for writing.
>> Opens the file for appending.
+< Opens the file for both reading and writing.
+> Opens the file for both reading and writing.
| (before file Treat file as command into which Perl is to pipe text.
name)
| (after file Treat file as command from which input is to be piped to Perl.
name)
File Handling
 Closing a File
 close <FILEHANDLE>;
close LOGFILE;

 Reading from File


 <> operator Creative Perl
open (LOGFILE," /etc/logs/reclaim.log");
$line = < LOGFILE >; my @fileContent;
@fileContent = <FILE>;
 Writing to a File
open (LOGFILE,"> /etc/logs/reclaim.log");
print LOGFILE“This is Perl Session\n";
Pattern Matching
 Searching and Replacing patterns in a given
string.
 Matching and Substitution
 Patterns more properly known as regular
expressions.
 Regular Expressions
 A generic rule describing a set of strings.
 DVR_*
 *_DVR
Pattern Matching
 Atoms
 The fundamental building blocks of a regular expression.

Atom Matches Example Matches Doesn't Match

. Any character except b.b Bob bb


newline
List of characters Any one of those a[Bb]c abc,aBc aDc,adc
in square brackets characters

Regular Anything that regular a(b.b)c abobc abbc


expression in expression matches
parentheses
Pattern Matching
 Quantifiers
 A quantifier is a modifier for an atom.
 Can be used to specify number of occurrence of an atom.
Quantifier Matches Example Matches Doesn't Match
* Zero or more instances of ab*c ac, abc abb
the atom
+ One or more instances of ab*c abc ac
the atom
? Zero or one instances of ab?c ac, abc abbc
the atom
{n} n instances of the atom ab{2}c abbc abbbc

{n,} At least n instances of the ab{2,}c abbc, .abbbc abc


atom
{nm} At least n, at most m ab{2,3}c abbc abbbbc
instances of the atom
Pattern Matching
Assertion Matches Example Matches Doesn't Match

^ Start of string ^fool foolish tomfoolery

$ End of string fool$ April fool foolish

\b Word boundary be\bside be side beside

\B Non-word boundary be\Bside beside be side


Pattern Matching
 Matching
 =~ operator
 $filename =~ /dat$/ && die "Can't use .dat files.\n";
 $oogles =~ /[fg][r]*oogle/

 Match Options
Switch Meaning

g Perform global matching

i Case-insensitive matching

o Evaluate the regular expression once only


Pattern Matching
 Extracting Matched Patterns in String
 Enclosing Pattern in Paranthesis
 $1, $2, $3… store matched pattern in paranthesis
if($fileName =~ m/([a-zA-Z0-9\-\_]+).([cC]+[pP]*)$/)
{
print “filename is $1 with extn $2\n”;
}

 Match Options

Switch Meaning

g Perform global matching

i Case-insensitive matching

o Evaluate the regular expression once only


Pattern Matching
 Substitution
 s/oldstring/nesstring/ operator
my $Training = “C Training”;
$Training =~ s/C/Perl/;
References
 Learning Perl (4th edition) - O'Reilly &
Associates
 Beginning Perl (1st edition) - Simon Cozens

 URLS
 http://books.perl.org/onlinebooks
 Free Perl Books -
freeprogrammingresources.com
 http://www.comp.leeds.ac.uk/Perl/

Вам также может понравиться