Post on 10-Apr-2015
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
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.
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
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.
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 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.
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.
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");
If an 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/valuesforeach $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 signedresult
<=> cmp
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”;
elseprint “Ok to proceed\n”;
Creative Perl
$a = 10;
Print “Value of input is $a\n” if $debug;
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
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;
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;
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"; }
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"; }
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.
Declarationsub 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;
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
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”;
}
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
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");
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.
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>;
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 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
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
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 OptionsSwitch 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/