Perl Training

40
PERL - A quick-and-dirty Language Somesh Saraf 20-21 Dec 2006

Transcript of Perl Training

Page 1: Perl Training

PERL- A quick-and-dirty Language

Somesh Saraf

20-21 Dec 2006

Page 2: Perl Training

Table of Contents

Prerequisites Perl Script First Perl Script Data Types Flow Control Subroutines Regular Expressions File Handling

Page 3: Perl Training

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)

Page 4: Perl Training

Perl Script

An ordinary 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.

Page 5: Perl Training

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"

Page 6: Perl Training

Scope of variables

Default global 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.

Page 7: Perl Training

Data Types

Small number of data types: scalars and arrays

Associative array : very special kind of array

Page 8: Perl Training

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;

Page 9: Perl Training

Data Types Numbers

100; # The number 42100.5; # A Foating point number100.000; # 10010E2; # 100

StringsCan 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.

Page 10: Perl Training

String Functions length

Returns the length of the string in bytes.

chompRemoves line ending characters from a string or array of strings.

chopRemoves the last character from a string or array of strings.

lcConverts all characters in the string to lower case.

ucConverts all characters in the string to upper case.

indexThis 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.

Page 11: Perl Training

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.

Page 12: Perl Training

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…

Page 13: Perl Training

Data Types - Arrays

Array can have mixed scalar types @items = (15, 45.67, "case");

If an array is evaluated in scalar context, it yields the number of elements in the array. my $word = @params;

print "$word\n";

Page 14: Perl Training

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’});

Page 15: Perl Training

Data Types – Associative Arrays

Keys and values may be treated as separate (ordinary) arrays

print keys %CR; print values %CR;

Extracting individual keys/valuesforeach $var (keys %CR) {

print "$var: \"$ $CR{$var}\".\n"; }

Page 16: Perl Training

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";

Page 17: Perl Training

Operators Relational Operators

Operator Numeric Context String Context

Equality == eq

Inequality != ne

Inequality with signedresult

<=> cmp

Greater than > gt

Greater than or equal to >= ge

Less than < lt

Less than or equal to <= le

Page 18: Perl Training

Conditional Expressions If (<condition>)

perl statement;else

perl statement;

If($a > 10)print “Value out of bound\n”;

elseprint “Ok to proceed\n”;

Creative Perl

$a = 10;

Print “Value of input is $a\n” if $debug;

Page 19: Perl Training

unless : The statement does not execute if the logical

expression is True and executes otherwise.

unless($directory eq “vxworks” )

{

perl statement;

….

}

while  The statement executes repeatedly until the logical expression is False.

Conditional Expressions

Page 20: Perl Training

Loops – whilewhile(<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;

Page 21: Perl Training

Loops- untiluntil(<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;

Page 22: Perl Training

Loops- for

The for statement resembles the one in Cfollowed 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"; }

Page 23: Perl Training

Loops- foreach

Iterates over 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"; }

Page 24: Perl Training

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.

Page 25: Perl Training

Subroutines Can be declared anywhere in a program. If more than one subroutine with the same name

declared only the last one is effective.

Declarationsub subroutine-name { statements }

sub PrintInfo{ print “This is first perl session\n”;}

Page 26: Perl Training

Subroutines

Subroutine call By prefixing the name with the & character.

&PrintInfo;

sub PrintInfo

{

print “This is first perl session\n”;

}

Page 27: Perl Training

Subroutines

Returning Values from Subroutines

&GetValue;

sub GetValue

{

return $value\n”;

}

(@return-a1, @return-a2) = &egsub4; sub egsub4 { local(@a1) = (a, b, c); local(@a2) = (d, e, f); return(@a1,@a2); }

Creative Perl

Page 28: Perl Training

SubroutinesPassing 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”;

}

Page 29: Perl Training

Subroutines Pass by Reference : Directly use @_

sub Increment{

@_[0]++;print “Value after increment $_[0]\n”;

}

Using shift to get parameterssub PrintError{

$ValToPrint= shift;$ValLength= shift;print “Value is $ValToPrint of Length ,$ValLength \n”;

}

Creative Perl

Same holds good for CommandLine Arguments

Page 30: Perl Training

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 fileopen (<FILEHANDLE>, “<Mode><FileName>");

open (LOGFILE, ">/etc/logs/reclaim.log");

Page 31: Perl Training

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 name)

Treat file as command into which Perl is to pipe text.

| (after file name)

Treat file as command from which input is to be piped to Perl.

Page 32: Perl Training

File Handling Closing a File

close <FILEHANDLE>;close LOGFILE;

Reading from File <> operator open (LOGFILE," /etc/logs/reclaim.log");$line = < LOGFILE >;

Writing to a Fileopen (LOGFILE,"> /etc/logs/reclaim.log");print LOGFILE“This is Perl Session\n";

Creative Perl

my @fileContent;

@fileContent = <FILE>;

Page 33: Perl Training

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

Page 34: Perl Training

Pattern Matching

Atoms The fundamental building blocks of a regular expression.

Atom Matches Example Matches Doesn't Match

. Any character except newline

b.b Bob bb

List of characters in square brackets

Any one of those characters

a[Bb]c abc,aBc aDc,adc

Regular expression in parentheses

Anything that regular expression matches

a(b.b)c abobc abbc

Page 35: Perl Training

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 the atom

ab*c ac, abc abb

+ One or more instances of the atom

ab*c abc ac

? Zero or one instances of the atom

ab?c ac, abc abbc

{n} n instances of the atom ab{2}c abbc abbbc

{n,} At least n instances of the atom

ab{2,}c abbc, .abbbc abc

{nm} At least n, at most m instances of the atom

ab{2,3}c abbc abbbbc

Page 36: Perl Training

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

Page 37: Perl Training

Pattern Matching Matching

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

Match OptionsSwitch Meaning

g Perform global matching

i Case-insensitive matching

o Evaluate the regular expression once only

Page 38: Perl Training

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

Page 39: Perl Training

Pattern Matching

Substitution s/oldstring/nesstring/ operator

my $Training = “C Training”;

$Training =~ s/C/Perl/;

Page 40: Perl Training

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/