22
 DOCUMENTTYPE 1 (22) TypeUnitOrDepartmentHere TypeYourNameHere TypeDateHere PERL Training ± 5 th to 7 th OCT 2010 Day 1 : Scripting is mostly use din automation, Coding ( programming ) lang needs to be complied and intermediate code is generated NO DATA TYPES in scripting , hence kind of data can b e used . Text processing is easy with scripting ( regular expression in automation) PERL : Pratical Extraction & Report Lauguage For details : ³Cpan.org´ ± Inbuilt modules are present , you can use from here. Scripting : Types of data : $ scalar @ list % associate array PRINT & STDIN : #!C:/PERL/bin/PERL51~1.EXE ±w Print ³enter your name´; $name=<STDIN> Print ³Hello, @name´; #interpolation CHOP: chop($name);# chop will chop ANY last character at the end When user clicks on ENTER , it takes as ³CARRIAGE RETURN´ Hence after you input any data in <STDIN>, It will also take in LAST character as ENTER ( one lone of blank data ) SO use CHOP to take only the exact data required  Arithmetic operation :  All input by default is a STRING µ+¶ always converts any input to NUMERICAL values ALWAYS. So when you give a string say ³abc´ , its value converts to ZERO ,  As µ+¶ operator converts to numerical.

PERL Training 5-7 Oct

Embed Size (px)

Citation preview

Page 1: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 1/22

 

DOCUMENTTYPE 1 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

PERL Training ± 5th to 7th OCT 2010

Day 1 :

Scripting is mostly use din automation,Coding ( programming ) lang needs to be complied and intermediate code is generated

NO DATA TYPES in scripting , hence kind of data can be used .Text processing is easy with scripting ( regular expression in automation)

PERL : Pratical Extraction & Report Lauguage

For details :

³Cpan.org´ ± Inbuilt modules are present , you can use from here.

Scripting :

Types of data :

$ scalar @ list% associate array

PRINT & STDIN :

#!C:/PERL/bin/PERL51~1.EXE ±w

Print ³enter your name´;

$name=<STDIN>

Print ³Hello, @name´; #interpolation

CHOP:

chop($name);# chop will chop ANY last character at the endWhen user clicks on ENTER , it takes as ³CARRIAGE RETURN´

Hence after you input any data in <STDIN>,It will also take in LAST character as ENTER ( one lone of blank data )SO use CHOP to take only the exact data required

 Arithmetic operation :

 All input by default is a STRING

µ+¶ always converts any input to NUMERICAL values ALWAYS.

So when you give a string say ³abc´ , its value converts to ZERO , As µ+¶ operator converts to numerical.

Page 2: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 2/22

 

DOCUMENTTYPE 2 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

So when user inputs 10 + abc = 10

34abc+10 = 44 ( as 34 is tak en , after that its ZERO value , till it finds numerical. Abc34 + 10 = 10 ( as abc is alreasy zero , so it stops scanning for numerical.

Concatenating :

$concatenate="firstword"."secondword";print "$concatenate\n";

µ.¶ DOT operator is concatenation , and has HIGHER PRIORITY for DOT than ADDITION (+)

#!C:/Perl/bin/PERL51~1.EXE ±w

-w is same as ³Use warnings´

µ¶ SINGLE quote , interpolation does not happen

$num1=2.7; # you can store any data type , also DECIMAL$num2=4;$num3=$num1+$num2;print "sum is $num3\n";

by DEFAULT all variable are GLOBAL.

To make it local , use LOCAL or MY

 A small difference between LOCAL & MYYou can see the difference in SUBROUTINES.

Lists & arrays

@myArray=(1,2,3,4,5,"sush",5865,"C+++"); # array or list can hold any type of dataprint "array is : @myArray\n";

print "my first element is : $myArray[0] \n"; # $ is used here , as one at a time is taken , hence scalar 

NO NEED to allocate MEMORY or space as in C programming ,It is dynamically allocated ( can be expand ed & shrunk )

In C prog you need to give lika Array = [4] ; ( Allocating memory )

$myLastnum=$myArray[$#myArray]; #this will access last number - $#myArray

$#myArray --- HASH itself is an operator that gives the LAST INDEX value of an array.

SLICING :

Page 3: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 3/22

 

DOCUMENTTYPE 3 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

 Accessing many elements from one array

@array1=@myArray[0,2,4];That is , it will take elements pointing by listed indexs , so its an array.

@array1=@myArray[0,2,3];# creating a array from an array , when LHS is $ , it can store only ONE element

What if LHS is scalar ie. $ then ?? but RHS is an array, what will happen .

If @ is used in LHS , even for SINGLE element , you can in future add more elements

But if $ is used in LHS & @ on RHS then ,as array pushes one value each time , slicing holds onl y ONE element in Scalar , so only LAST element

is saved

$Scalar=@myArray[0,1,3];print "whats this : $Scalar\n"; # takes only LAST index value element .

LENGTH of Array can also be got as :

$length=@myArray;

print "length of array is: $length \n";

or :

$myLastnum=$myArray[$#myArray]; #this will access last INDEX- $#myArray

LOOPS :

#!C:/Perl/bin/PERL51~1.EXE -w

#Loops

# WHILE loop

$i=1;

while($i<=5)

{print "i is $i\n";++$i;

}

#create an array , print all elements in below format# at o index value is : 20#at 1 index value is: 10

Page 4: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 4/22

 

DOCUMENTTYPE 4 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

@myArray=(10,20,30,40,50);

#$i=0;

while ($i<=$#myArray){

print "index is $i and value is $myArray[$i] \n";++$i;

}

#FOR EACH loop , mainly to process a LIST, scalar followed by a list

foreach $v (@myArray) #more like foreach $v ( 1,2,3,4,5){

print "Value is $v \n";

}

foreach (@myArray) #this is without a SCALAR variable{

print "Value is without a variable $_ \n";}

#Create array by name arra y1 amd store few city names#defined a foreach loop which update each array element as city_KN

@arraycity=(Delhi,Bombay,Bangalore);

foreach $c (@arraycity)

{print "List of cities after impeding is $c"."_KN"." \n";

}

#!C:/Perl/bin/PERL51~1.EXE -w

#String functions

$str1="bangalore";print "my string is $str1\n"; #to show current string$x=uc($str1);print "x is $x\n"; # this does not update exsisting string , only give new value

#create array by empname , store few emp names.

#define for loop to update each element in below format#uppercase of empname : lengthofempname#RAM:3#RADHA:5

@empName=(Sush,Saha,RAM,DEEpu);print "Names of employess at present @empName \n";

foreach $e (@empName) # takes one string at a time and assigns to scalar 

{$e=uc($e).":".length($e);

Page 5: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 5/22

 

DOCUMENTTYPE 5 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

}

print join(" \n",@empName);

JOIN :

Join function creates a single scalar with array elements delimiting with specified chatercter .

$join=join("-",@empName); # joins to one scalar variableprint $join;

SPLIT :

Main ideas of a DATA STRCTURE :

Create AccessDlete AddReplace

PUSH POPSHIFT or UNSHIFT

PUSH ± will add element at rear endUNSHIFT will add in front end

POP ± will remove from rear endSHIFT ± will remove from front end

SPLICE :

InsertDeleteReplace

splice(@numlist,2,3,"x","y","z"); # this is used to REPLACE the elements

#syntax(@array,INDEX VALUE, NUMBER of ELEMENTS, Values to replace); if string is smaller, thenextra will get appended

splice (@numlist,$i,1);splice (@numlist,$i,1,"replaced"); # if NO value is specified , then it DELETES the value

COMPARISIONS:

Cmp for string comparision : by default shows in Decending , by ASCII value

Page 6: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 6/22

 

DOCUMENTTYPE 6 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

<=>: for numerical comparision : by default shows in Ascending , by ASCII value

If you want STRING in Ascending or Numerical in Decending then ,

@slist=sort {$b cmp $a } (@numlist);

@slist1=sort {$a <=> $b } (@num1);

$b then $a shows Higest to lowest ± Decending order 

$a then $b shows lowest to highest ± Ascending order 

Reverse ± simply reverse string ( no sorting nothing)

@x=reverse(@num1);

print "after reverse @x\n";

DAY 2 :

PUSH fuction RETURNS the length of the updated array.

@a1=(1,2);print "array is @a1 \n";@b1=push (@a1,3);

print "now array is @b1 \n"; #PUSH fuction RETURNS the length of the updated array.

print "now array is @b1 \n"; #PUSH fuction RETURNS the length of the updated array.

($x,@a2)=@a1; # stores x= first element and @a2 = all other elements in RHS array($x,$y)=@a1 ; # stores x= first element , y = second element(@a3,$z)=@a1; # stores a3 has all array , and z = null

while (<STDIN>)

{chop($_);#If you use CHOMP , error , as it chomps off even ENTER key , not realising its END of array  push(@num,$_);

}

Page 7: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 7/22

 

DOCUMENTTYPE 7 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

HASH :

Memory management is good in HASH , than list .

Every Key has a VALUE ,There are 3 ways of defining a HASH list.

SYNTAX 1: always use FLOWER BRACKET when defining individually .

$empID{100}="044 -8467";$empID{101}="022 -841367";$empID{102}="033 -238467";$empID{103}="012 -843367";

print "100 contact is : $empID{100} \n";print "102 contact is : $empID{102} \n";

Syntax 2 :

Or if using PERCENTAGE symbol :

%fruits=(³apple´,´red´,´papaya´,´yellow´); -- LIST context , hence PAIR should be present ,Else it will return a NULL value .

Print ³apple color is : $fruit{apple} \n´;

So -> apple is key , red is value , papaya is key , yellow is value

Syntax 3 : this is best , with no confusions

%myHash=(³A´=>65,´B´=>34,´C´=>22,´D´=>87);Print ³A asciss code is : $myHash{A} \n´;

Key functionality :

@keylist= keys %empID; # use KEY functionality to get all keys , and push to an array

print "Emp ID are : @keylist \n";

KEY order is NOT in SAME order .

 As memeory allocation is dynamic , so order is mixed

IXA module : import & use to SORT and print in order 

Values functionalty :

Keys %myHash ± gives KEYS of hash listValues %myHash ± gives only VALUES of hash list

Page 8: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 8/22

 

DOCUMENTTYPE 8 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

print "@{[%hash3]}"; # to print all elements inside a HASH

SUBROUTINES :

#used to get back a value from called function to calling function Arguments are stored in ³@_´ by default

DISPLAY :May pass the values , or may not pass the values or arguments.

sub display {

print "control is in display function \n";print "display :@_ \n"; # by default , any arguments passed into a function , is stored is an array}

print "control is main routine \n";display;print "control is back to main routine \n";

display(10);display("hello","how");

print "List with array return is @result \n" ; #this takes full array as one big SCALAR , and prints , thatwhy printing HASH is circus with many brackets.

print "Odd number list using PRINT ". AddOdd(@myArray)."\n"; #this concatenation can only PRINTONE SCALAR value , so LENGTH of Odd list is shown

MY and LOCAL variables :

MY is only for a particular blockLOCAL is accessible to all its CHILD blocks too . Scope is for all blocks which calls that function .

BEGIN and END :

BEGIN : BEGIN is inbuild procedure , making variables as STATIC# hence using BEGIN updates the value of x each time after a subroutinue ( so next time you can buildon previous value

END # Need not CALL the function END , it WILL execute anyways if its defined under END{print "End of script \n";}

 AUTOLOAD :

Page 9: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 9/22

 

DOCUMENTTYPE 9 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

 AUTOLOAD { # AUTOLOAD will have an inbuilt scalar variable ,when something is not defined ,

 Autoload executesprint " this is Autoload $AUTOLOAD \n";}Program :

 AUTOLOAD { # AUTOLOAD will have an inbuilt scalar variable ,when something is not defined , Autoload executes

print " this is Autoload $AUTOLOAD \n";}

sub display {

print "this is in display \n";}#sub show {

#print "this is in SHOW\n";#}

print "this is MAIN block\n";display();

show(); # since SHOW is not defined , or commented , it will show AUTOLOAD value

Regular Expressions :

Most of the time used in FILE HANDLING

1. To Find our patterns2. Find our patterns and replace them

 Applys on strings

FORMAT : $myString=~m/pattern/

³m´ stands for MATCHPattern stands for the pattern you want to search

 Above code return 1 if $myString consists of pattern you are looking for Otherwise it will return null or zero.

$result=$myString=~m/pattern/

If $result is 1 , then pattern found in $myString .

^alphabet ± means the word should START from that character 

Ex: $myString2=("Sushma is my name");

Page 10: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 10/22

 

DOCUMENTTYPE 10 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

if($myString2=~m/^S/)

then TRUE , as string STARTS with ³S´

alphabet$ will serach for LAST character in string

$myString2=~m/^[aieou]/i/)

Last slash ³I´ means its

^ check string stars with$ edns with

[] a charater class

+previous character, check wether previous occurs miimun once , max ay time ( mandatory )

*Applicable previous, check wheather , check weather previous occurs , min ZERO , max One time (optional)

?applicable , min Zero , max 1 time ( not unlimited )

/\.txt$/ if pattern must END with ³.txt´

When using ³.´ Or ³$´ as a symbol in pattern , use BACKLASH ³\´

Check string contains atleast 3 digit number :

/[0-9][0-9][0-9]/

Minimum 2 digits , max 3 digits:

/[0-9][0-9][0-9]?/ last digit is optional 

³/d´ also same as numbers [0-9] instead

\/d+$/ same as \[0-9]+$/

xxx-xxxxxxx

Page 11: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 11/22

 

DOCUMENTTYPE 11 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

x indicates numbers

\^[0-9]{3}-[0-9]{10}$/

Or 

\^\d{3}-\d{10}$/

Minimum 2 times , max any number , the {2,3} so min 2 , max 3If min 2 and max anything then {2,}

Check second character is vowel

Each DOT stands for ONE charater .

/^.[aeiou]/ this means , first character is DOT ( can be anything, number or alphabet )From second chart should be vowel

/^«[aeiou]/ this means , first 3 characters is 3 DOT¶s ( can be anything, number or alphabet )From second chart should be vowel

First charter is must be alphabet and last must be number 

/^[a-z].*[0-9]$/

Here ³DOT and STAR ³ means DOT can have any character , then STAR can be any number of charecters.

Contains abc in order not in sequence

/a.*b.*c/

Start with a means /^a.*b.*c/

Escape characters :

\b : to check if word is there word boundry

\bwork\b/i

For one space ³\s´

Page 12: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 12/22

 

DOCUMENTTYPE 12 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

/abc\s+xyz/ \s+ is once and unlimited\s* will be zero or any number 

DAY 3 :

Global Pattern

@a=$mystr=~m/[0-9][0-9] /g; 

This makes to check pattern to check in FULL string ,Else simple pattern search , look sonly inside FIRST pattern

#Regular expressions , to chekk which pattern made it MATCH , GLOBAL pattern#GLOBAL pattern searchs ALL occurnces in entire string . else simple checks only for FIRSToccurrence

^ - start with$ - end with+ - min once , max anything³*´ ± zero or max once ( optional ) , it might or might not be there .? ± min zero or max once³. ³- one character \b ± word boundry

\s ± space() ± bound ry\d can be used instead of [0-9]\w can be used instead of valid alphabet , which matches all these : [0 -9][a-z][A-Z] and ³_´underscore.

() boundry ± starts and ends with same , used for BACk reference

Older explanation :

³+previous character, check wether previous occurs miimun once , max ay time ( mandatory )

*Applicable previous, check wheather , check weather previous occurs , min ZERO , max One time (optional)

?applicable , min Zero , max 1 time ( not unlimited )´

() boundry :

Values are stored in buffers names \1 and \2 etc«. to refer it back

Page 13: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 13/22

Page 14: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 14/22

 

DOCUMENTTYPE 14 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

print "@a"; # this takes all charcters that is NOT a NUMBER , and "ig" together makes globaland case sensitive

SUBSTITUTION :

$str = "city name is mysore";

$str=~s/my/BANG/; # this replaces "my" with "BANG" and keeps all extra charaters as it is

print "now my str is $str\n";

OUTPUT : city name is BANGsore

$str=" a house is my city ";

# check if multiple spaces are seen , remove and keep only ONE space$str=~s/\s+/ /g; # if you give"\s" it types it , so hust give a SPACE to replace by a spaceprint " now string is:$str\n";

³city name 10 and 200 mysore´

~s/\b(\w+)(e)\b/$2$1/g;  # this is searching only for any WORD pattern .as ³\w´ includes anything as 0-9 , a-z,A-Z, and Unsderscore. 

~s/\b(\w+)(e)\b/\2\1/g;

Use \1 or $1 , \2 or $2

 Above result is making ³nam´ into $1 , then ³e´ into $2,Then pattern in storing ³mysor´ in $1 and ³e´ in $2 .

$1 and $2 stores only the PATTERN and not the actual data .

So Output will be :

City enam 10 and 200 emysore 

REFERENCES :

In regular Functions , any value was passed as ONE big ARRAY !!If you need to keeo that structure as it is , use References.

Page 15: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 15/22

 

DOCUMENTTYPE 15 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

Refernce is a scalar , as it stores the Address of FIRST element of an array .

$aref =\@array; - Array reference

$href =\%hash; - hash referemce

$sref=\$variable; - variable or scalar referenc

 As REFERENCE is a sclar , value is always stored in a SCALAR , And can be used on any type of data ± array,hash or scalar.

This reference prints the ADDRESS of that Array/hash or scalar 

REF function :

to find WHAT is format of the data in that address , so that you can perform functions based onthe FORMAT

$x=ref ($href);

print "x is $x\n";

if($x eq "HASH")#ref only understands SCALAR,ARRAY,HASH words to find WHAT is format of the data inthat address{print "href is reference HASH\n";

Equal to :

Str1 eq str2 is for STRING valuesNum1 == num2 for NUMERICAL values

less than ltgreater gtgreter than and equal to : geless than or equal : le

#To use Reference and print an array :

Page 16: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 16/22

 

DOCUMENTTYPE 16 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

@array1=(1,2,3,4);

$aref=\@array1;

print " first element is $array1[0] \n";print " first element is ${$aref}[0] \n";

print " the arary is : @array1 \n";print " the arary is : @{$aref} \n";

print "Last element is : $#array1 \n";print "Last element is : $#{$aref} \n";

 just replace ³arrayname´ with ³$aref´ , as above example.

Use {} flower bracket to make the code more visible and neat

To find LENGTH :

$len1=@array1;print "length is $len1 \n";

give an ARRAY into a SCALAR , it always takes the LENGTH , ( not the first element of thearray into scalar !!!!)

QUOTES :

#%myHash=("apple","red","grapes","green");

%myHash=qw(apple red grapes green); # use "qw" if all are STRINGS , else have to QUOTEeach element manually

#if you need not perform any arithmetic operations then you can QUO TEthat too, such as emp ID

 Anonymous ARRAY or HASH :

Usually in big data size, you will any way work only on the data ,So why wate a variable by naming an Array or Hash ,So simply create data directly by using a Reference .

#@a1=(1,3,4); # so you are SAVING a variable a1 , as you are anyways refrening only to thatarray block , and not the NAME!#$ref1=\@a1;

$ref2=[3,4,2];

Page 17: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 17/22

 

DOCUMENTTYPE 17 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

#[] square brackets creates an anonymous ARRAY /LIST

block print "ref2 is $ref2";

#Anonymous HASH

$ref={"A",65,"B",66};

#{} flower brackets creates an anonymous HASH block

print "hash refrence is $ref\n";

Complex Array and HASH :

#complex arrays

my @myarray=([2,3,4],"java",[3,7,9],"excel");

one array which has refrence array or strings inside one array .

So write a program , to identify if it¶s a ARRAY or string,If its an ARRAY inside an Array ,Then print full array , else just that string .

--++++++++++++++++++++++++++++#complex arrays

my @myarray=([2,3,4],"java",[3,7,9],"excel");

print "array is : @myarray \n";

$x=ref($myarray[0]);print "x is $x \n";

#get output as :

#index 0 : elements 2,3,4#index 1 : elements java#index 2 : elements 3,7,9#index 3 : elements excel

$ref1=\@myarray;

print "Refernce of first element is $ref1 \n";

#foreach (@{$ref1})

Page 18: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 18/22

 

DOCUMENTTYPE 18 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

#{#print "Index is $_ and element is @{$ref1}[$_]";

#}

$x=0;#foreach (@myarray)

foreach (@{$ref1}) # above line is the same as this{

if (ref($_) eq "ARRAY") # here is data type is ARRAY , then $_ will hold the word ARRAY{print "$x is : @{$_} \n";

}else{print "$x is : $_ \n";}++$x;

}

++++++++++++++++++++++++++++++++++

Complex HASH :

print "@{$myHash{$ _}}"; # this prints the ARRAY that is pointed by the reference key

{$myHash{$_}} this shows the start of an ARRAY

@ {$myHash{$_}} @ the rate lists out all the strings in that above poi nted array .

NOTE :

REALLY SCARY ± Want to try ³Use Anonymous HASH on LSH , and COMPLEX HASH , with

anonymous HASH & Array¶s inside on RHS . ( You µll go MAD I m sure !!! )

FILE Handling :

By default its READ mode, if no symbol is preceeded before the file name.

Regular Expressions are extensively used in File Handling , as you usually use to find apattern and retrieve or write accordingly .

Page 19: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 19/22

 

DOCUMENTTYPE 19 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

Modes in File handling :

³<´ READ³>´WRITE, erase all exsitng data³>>´ append , add to existing data³+<´ read and write mode , if file exits,then write to it .(cant CREATE a file)³>+´ write plus read mode,if file does not exits,it CREATES file,but OVERWRITTES³>>+´ append and read mode, if file does not exits,it CREATES file,but adds at the LAST .

++++++++++++++++++++++++++++++++++++++++++++++Open(FH,´D:\\flower.txt´) || die ³file cannot open \n´;

While (<FH>)

{print $_;}

Close(FH);++++++++++++++++++++++++++

Open(FH,´<D:\\flower.txt´) || die ³file cannot open \n´;

 Above line : All data inside D:\\ drive and flower.txt loads into FH,³<´ reads from the file And remain in that cache till you close FH.

³||´ means OR , so if cannot open,then print .

Print ³Hello´; Actually meansPrint STDOUT ³Hello´;STDOUT throws display to screen ± it¶s a Handler 

You can define any File Handler in any name you want .

Like FH , WFH , FH1 , FH2 .. etcIts just a name given by you .

Page 20: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 20/22

 

DOCUMENTTYPE 20 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

PACKAGES and MODULES :Store it as extension .pm ( means PERL MODULE)

Every package MUST return a TRUE Value ( or 1 ) !!

# PACKAGES AND MODULES#design this below Package/module then use it in any other normal script

++++++++++++++++++ below file name is saved as ³ConverterPackage.pm´

package converter ; # package is a name space

sub uppercase {

my $r=uc($_[0]);print "result is $r \n";

}

sub lowercase {

my $r=lc($_[0]);print "result is $r \n";

}

1; # this is to return a TRUE value

++++++++++++++++++++++++

#Use that Converter Package to work on this script

use ConverterPackage; # File Name with ".pm" extension

converter::uppercase("flower"); # LHS will be that BIG function , also called NAMESPACE, and on RHS is the inner function name.converter::lowercase("FLOwer");

Page 21: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 21/22

 

DOCUMENTTYPE 21 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

+++++++++++++++++++++++++++++

If the Pacxkage file is not in the SAME FOLDER AS YOUR ³.PL´ FILE,then thereis a inbuilt function ³@INC´Gets pathsof where all PERL is present ,So when you say :

USE Converter ,This statement actually invokes @INC ,Which inturns looks for the ³ConveterPackage.pm´ file in all the PATHS definedinside @INC,If It dint find it under any of those , then throws error ,

Telling it dint find the file !

How to Download a module and use it :

Refer : ³CommandpromptCodes.docx´ in the PERL folder that I have saved,it¶s a copy of entire Command prompt screen.

Goto ³cpan.org´Goto PERL Module ->

CPAN search -> look for IxHash (This is used to SORT an array)

Open any of listedDownloadSave to any folder 

Extract the zip file

Goto command prompt :

Goto path where you saved that module

Then type in cmd :C:\>xyzWhateverPath>perl Makefile.pl this EXECUTES the PERL fileC:\>xyzWhateverPath>perl Build.pl this EXECUTES the build file

C:\>build test this is to simply check if BUILD has been complied or not !C:\>build install this INSTALLS the build contents

 After this , it will show what all Tie-IxHash installs :

Page 22: PERL Training 5-7 Oct

8/8/2019 PERL Training 5-7 Oct

http://slidepdf.com/reader/full/perl-training-5-7-oct 22/22

 

DOCUMENTTYPE 22 (22)

TypeUnitOrDepartmentHereTypeYourNameHere TypeDateHere

Building Tie-IxHash

Installing C:\Perl\site\lib\Tie\IxHash.pmInstalling C: \Perl\man\man3\Tie.IxHash.3Installing C:\Perl\html\site\lib\Tie\IxHash.html

#How to Download a module and use it :

use Tie::IxHash; #This is to CALL the module you have usedtie (%foo,"Tie::IxHash"); # this TIES only the Array or string that YOU want ,not

 ALL

$foo{c} = 3;$foo{b} = 2;$foo{a} = 1;

print keys(%foo);