Sunteți pe pagina 1din 70

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

PERL Practical Extraction & Report Language


Silent features of script language: They are interpretor languages i.e., compile 1 and execute 1 at a time They do not have entry point No data types Edited in text editor Build stage or compile stage is not required They are fast when compared to compiler languages like c, c++ Perl is extensively used from long time in CGI Common Gateway Interface

Advantages:1. 2. 3. 4. 5. 6. Text processing , file processing User interface programs Database programs Networking System administration Automation scripts (extensively used)

Perl is case sensitive language Features of Perl: a. b. c. d. e. f. g. Case sensitive Statements are terminated with ; except last statement It is both procedural and object oriented language It is simple , easy to learn It can be embedded in languages like c , cpp Have an extension of .pl Free from www.perl.com

Checking version: perl v man perl --- for manual pages in linux man perlintro

PRACTICE MAKES MAN PERFECT .

Page 1

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

file1.pl Shebang line Path Variable #! /usr/bin/perl -w print hello perl world; $x = 10; print ($x, \n); For warning to active Without paranthesis called as Named operator optional With paranthesis called as perl operator

Running Perl: perl file1.pl ---------------- using perl interpretor hello perl world 10 chmod u+x file1.pl --------- changing permissions to file file1.pl --------- to run without interpretor perl can also be used interactively perl print HELLO WORLD\n; input $x = 10 ; print $x, \n; ctrl+d HELLO WORLD 10 output Identifiers in perl: Can use alphabets , numbers and _ Cannot start with digit Literals : 1. 2. 3. 4. Numbers Strings List Undef

PRACTICE MAKES MAN PERFECT .

Page 2

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Numbers : a. Intergers : i. ii. iii. iv. Decimals Hex Oct Binary

b. Real (64 bit double precision ) (signed) _ can be included at any position except first place for numbers readability. If we use at first position it is interpreted as string. Ex : $x = 10; = 012; =0xA; =0b1010_1010; 2. Strings:- Strings can be either double quoted or single quoted can be of any size. No need to allocate any memory. They can sshrink or grow automatically. A string can be without quote if it is single word called ass bare word Ex : $name = ram ------- bare word

Guideline: not use bare word string because system will search whether subroutine with that name is present or not , which increases processing time. Nesting of quotes double quote in double quote or single quote in single quote is not permited . Nesting of or is permited. $str = she said , I love perl,and laughed; $str = she said , \I love perl\,and laughed; $str = qq(she said , I love perl,and laughed); $str = q(she said , I love perl,and laughed); qq places double quote around the string q places single quote around the string.

PRACTICE MAKES MAN PERFECT .

Page 3

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Escape sequences : (text formatting) \n,\t,\b,\ddd,\xHH,\x{HHHH} Escape characters \ \t \n \r \f \b \a \e \ddd \xHH \x{HHHH} \c[ \cA = ctrl + A Transulation escapes : Escape characters \u \U \l \L \E \q print hello world \n; hello world print \u hello world \n; Hello world print \U hello world \n; HELLO WORLD print \U hello\E world \n; HELLO world $str = HELLO WORLD; print \l $str; hello world Means Used to convert first char to upper case Entire string to upper case First char to lower case Entire string to lower case Ending transulation Quote all alphanumeric characters Means Double quotation mark Tab Newline Return Form feed Backspace Alarm (bell) Escape Octal escape Hex char Unicode char Control char

PRACTICE MAKES MAN PERFECT .

Page 4

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

ASCII 0 to 255 (only English) UNICODE All languages 0 to 65535 0 to 255 English languages 3. List: Collection of scalar values. $x = (10,20, ram , sita , 12.5); Nesting of list has no effect (10, 20, ( ram ) , sita , 12.5 )
ignored

The inner braces are ignored. This is called flattening of nested list. 4. undef: $x = 10; $x = undef; Undef $x; Variable : 6 types Scalar Indexed array Associated array / Hash File handle Glob Reference
same Will have undefined or no value

Scalar : Prefixed with $ symbol $x = 10 ; $x = ram; $x = 12.5; print $x;

PRACTICE MAKES MAN PERFECT .

Page 5

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Indexed array : Used to store list of scalar values of any type. Prefixed with @ symbol. An ordered collection of scalar variables. Comma (,) is used to separate the elements. Arrays are dynamic in perl. Size will increase or decrease.

@arr = (10, 20, ram , sita , 12.5); Index 0 1 -5 -4 2 -3 3 -2 4 -1 -ve index

Last positive index is stored into the variable prefixed with $# print $#arr; 4 print $arr[0]; 10 print @arr; 1020ramsita12.5 print @arr; 10 20 ram sita 12.5

Accessing single element Without double quotes , no gaps between the elments Creates delimiter between the elements

The delimiter is store in a predefined variable $ $ = :: print @arr; 10::20::ram::sita::12.5 print @arr[1,3]; Always lower value 20::sita print @arr[1..3]; Always higher value 20::ram::sita Range operator

Numbers in variables Type Integer Floating Scientific

Example 123 1.23 1.23E4


Page 6

PRACTICE MAKES MAN PERFECT .

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Hex Oct Binary

0x123 0123 0b101010

3 . Associated Arrays / Hash : o Unordered collection of key value pairs. o Keys must be unique. o Prefix dereference is %. %ages = (ram, 20 , sita , 18 , laxman , 19); o Keys can be of any size but can be a reference. o By default keys are strings. print $ages{ram}; 20 print @ages{ram, laxman}; 20 19 print %ages; Order of retrival is not same as order of insertion ram20laxman19sita18 4. File Handle: Variables that are used to open files open(filehandle, mode , filename);
Unique identifier

No prefix. Ex : open (FH , file1.txt);

5. glob : Special type of variable that store any one of above 4 variable. Prefix is *. $x = 10; @x = (10 ,20 , sita , 15 , 1.25 ,ram ); %x = (ram, 20 , sita , 18 , laxman , 19); *y = *x;

*x any one of $x, @x, %x print $y ;


PRACTICE MAKES MAN PERFECT . Page 7

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

10 print @y; 10 20 ram sita 12.5 print $y[2]; ram print $y{ram}; 20 6. References : Used to store the address of another variable ( just like pointers in c) It is a scalar variable $a = 10; $r = \$a; \ address of operator print $$r; Global variables : $x = 10; @arr = ( );
Referencing

Dereferencing

The scope of the variable is the entire package in which they are created. Package is a name space. Packages are used to avoid clashes of names The scope of variable in a variable is till the next package declaration. Packages are not restricted by file bounds. Single package can spread across multiple files
file1.pl package p1; $x = 10; $y = 20; package p2; $z = 30; p1 $x $y $a package p1; $a = 15; file2.pl

PRACTICE MAKES MAN PERFECT .

Page 8

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

package p1;

File3.pl

require file1.pl; $a = 10; print $x; Print $p2::x;

Used for including a file if want to access the variable of that file

Accessing x of p1 in file1.pl

Access $x of p2 in file1.pl

:: scope resolution operator

Substitutions : There are three different types of substitutions 1. Variable 2. Backslash 3. Command Variable : Single quote Double quote Without quote No substitution Only scalar & list variables All the three scalar, list & hash

$x = 10; @x = (10, 20 , 30 ,40 ); %x = (ram , 10); print $x; - valid print @x; - valid print %x; -valid print $x; -valid print @x; -valid print %x; - not valid output is %x print $x; - not valid output is $x print @x; - not valid output is @x print %x; - not valid output is %x

PRACTICE MAKES MAN PERFECT .

Page 9

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Backslash : Backslash substitution works only in double quotes. Command substitution: Occurs when command placed in back tick (`) $l = `dir`; Back tick with double quote does not work. $l = `dir` Context: The same expression gives different results in which they are used. Scalar List Void @arr = (10, 20, 30, 40); $n = @arr; The above is scalar context. Perl understands one value return from the array , so it returns number of elements in the array. @Arr = @arr; The above is list context. Copies entire array arr to Arr. If we want to take i/p from keyboard while executing the code ie., interactively from user just like scanf in c <STDIN> ----- waits for input from keyboard 1. 2. 3. -not valid

$line = <STDIN>; Waits for only one input @lines = <stdin>; This is a perl program Welcome to perl world Ctrl+d ---- to terminate the input print hello, perl, world; print (hello, perl, world); hello perl world
PRACTICE MAKES MAN PERFECT .

List of arguments

Page 10

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Print (hello, perl) , world; Hello perl Print function : print filehandle list;

Ignored taken in void context

List of printable elements Default file handle is STDOUT

print ; ---- default argument is $_ print hello\n\twelcome\n; hello welcome $x = 10; Print x = , $x , \n; X = 10 Variables & constants can be used as boolen expressions returning true or false. True False Non-zero (same as C) 0 (zero) Array with atleast one element Undef String with atleast one character other than Array with 0 elements zero but $str = 00 is true String with single 0 Empty string & list List : One list can be assigned to other list provided left hand side are variables ($a, $b, $c) = (10, 20, 30); ($a, $b) = ( 10, 20 , 30);
Ignored in void context

($a, $b, $c, $d) = (10, 20, 30);


undef

($a, $b) = ($b, $a); -- swapping of a &b , a temporary variable is used internally. ($b, $c, $a) = ($a, $b, $c);
Rotating to right by one position PRACTICE MAKES MAN PERFECT . Page 11

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

$a = (10, 20, 30)


Evaluates from left to right & last is assigned Scalar context

$a = ($x = 10, $y = 2*x, $z = $x + $y); print $a; 30


list context

($a )= (10, 20, 30);

Paranthesis converts scalar context to list context.

Slices of list:

$a = (10, 20, 30,40,50)[2];

($a, $b) = (10, 20, 30,40,50)[1,3];

$a = (10, 20, 30,40,50)[1,3]; $a = (20,40); Indexed array: $myarr[9] = 100; Above statement create array of size 10 with tenth element is 100 & remaining elements undef. print $#myarr; --- returns index of last element 9 $myarr[99] = 1000; Increases the size of array to 100 $#myarr = 19 --- reduces the size of array to 20 elements
PRACTICE MAKES MAN PERFECT . Page 12 Both are same 40 is stored

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

@arr = (10,20,30, sita,50); print @arr\n; 10 20 30 sita 50 $= ; print @arr\n; 102030sita50 print $arr[2]; 30 $arr[2]= ram; @arr[1,4] = (25 , 40); print @arr\n 10 25 ram sita 40 Hash / Associated array : %ages = (ram, 20, sita, 18 , laxman, 19); $ages {ram} = 25 ; ------ modifying single key value @ages{ram, sita} = (25,23) --- modifying a list of keys $ages{hari} = 35; ------ inserting a new key-value pair @ages = %ages; Together to get spaces between the elements of hash print @ages %ages = (ram=>20, sita=> 18 ,laxman=> 19); ------ another format of key value pair

Operators
Arithmetic operators: + Real division 10/3 = 3.33 .(14 decimals) Exponentiation operator

**
10.5 % 3.5 =1 truncated

** is used to find either power or root of a number print 5 ** 3 ; 125 print 64 ** (1/3); 4

PRACTICE MAKES MAN PERFECT .

Page 13

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Comparision operator: Numbers Symbol > >= < <= == != <=> Strings Equivalent named operator Gt Ge Lt Le Eq Ne Cmp Usage greater than greater than or equal to lessthan less than or equal to equals to not equal 3 way comparison operator

The 3 way comparison operator returns following expr1 <=> exp2 or str1 cmp str2 Returns 1 0 -1 When expr1 > expr2 expr1 = expr2 expr1 < expr2

Logical operator: ! not && and || or ---high precedence ---low precedence

precedence of symbol is high $v = 0; print $v && 1..10; 0 ------ 10 And operator has higher precedence print $v and 1..10; 0 Bitwise operator: & | ~ << >>

Logical shift

PRACTICE MAKES MAN PERFECT .

Page 14

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Increment ++ and decrement -- are available in both prefix and postfix notations Increment operator works on strings print ++($str = item5); item6 print ++($str = ab); ac $str = AZ; print ++$str; BA $str1 = a5b; print $str1; ---- does not work with number in between the characters Assignment operator : $str = = is assignment operator. Short hand +=, -=

Conditional operator : ? : is the conditional operator Cconcatination operator (.) : Used to join two strings. $str = hello; print $str. world; hello world printf $str. perl. world; hello perl world $str1 = 25;
PRACTICE MAKES MAN PERFECT . Page 15

$a =10; $b =20; $res = $a > $b ? $a : $b; ($a > $b ) ? $a : $b = 35 ; print $b; 35

---- modifies the greater value variable content

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

$str2 = 35; printf ($str1.$str2); 2535 Repeat operator:


String x count; print abc x 3; abcabcabc print 123x3; 123123123 ------ only number without quotes, repeat operator works

To create an array with 100 elements & initialize them with 0 @arr = (0) x100; Range operator : Lower .. higher print 1..10; 1 2 3 4 5 6 7 8 9 10 If (5..10) --------------- condition true between 5 and 10 Another version :: Binding operator : It is used for pattern searching. $str =~ pattern (or) regular expression In scalar context returns 1 if pattern is found. perl (interactive mode) $str = this is a perl string in perl class using perl regular expression; if ($str =~ /perl/) { print matched; } else
PRACTICE MAKES MAN PERFECT . Page 16

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

{ print not matched; } @n = $str =~ /perl/gi print @n\n; perl perl perl File test operator: -r filename -w -x -e -o -z -f -d -s -m Read permission Write permission Executable Existence of file in file system Ownership Zero size file Plain file Directory Socket Modification time FLOW CONTROL I selective : if (condition) { Set of statements; } Braces are always required even if it has only one statement Another version : statement if (condition) ------- to avoid braces for single statement i ignore case g global search

unless (condition) {

PRACTICE MAKES MAN PERFECT .

Page 17

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Statements } statement unless (condition) unless is used to negate the search condition.

if (condition) { } elsif (condition) { } else { } optional

II Iterative : 1. while (condition) { statements } 2. statement while (condition); 3. negate the condition using until until (condition) { statements } 4. for (init exp ; test exp ; update exp) { statements }

PRACTICE MAKES MAN PERFECT .

Page 18

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

5. foreach var (list) { Statements }

If we do not write any variable $_ is used by default

@names = qw (ram sita laxman); or (ram, sita , laxman); foreach (@names) foreach $var (@names) { { print $_ ; / print; print $var; print \n; print \n; } } Output : ram sita laxman Jump statements C language Break Continue goto label Perl last last label; next next label goto label exit code 0 successful exit non zero -- failure

loop1 : for( $i = 0; $i < 10 ; $i++) { loop2 : for( $j = 0; $j < 10 ; $j++) { last if ($j == 5) ; print ($i , $j\n); } }
PRACTICE MAKES MAN PERFECT . Page 19

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

loop1 : for( $i = 0; $i < 10 ; $i++) { loop2 : for( $j = 0; $j < 10 ; $j++) { last loop1 if ($j == 5) ; print ($i , $j\n); } }

Do while: $n = do { Statements ; }; --- all are executed sequentially

The block returns value of last exp evaluated. do { Statements ; }while (condition); Note : last and next cannot be used in the do block . we cannot jump out of loop.

Anonymous / Bare block : { statements }

PRACTICE MAKES MAN PERFECT .

Page 20

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

In the bare block last anrd next have no meaning the just jump out of the bare block. { do { Statements ; Next/last; }while (condition); } do { { Statements ; Next/last; } }while (condition);

Built in functions Functions in perl are also called named operators print 10,20,30; print (10,20,30); Named operators : Scalar named operators ----- only one argument List ----- 0 or more arguments No arguments named operator function

PRACTICE MAKES MAN PERFECT .

Page 21

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

I. String functions: 1. chop string-variable chop list chop The default argument for chop is $_; $str = rama; $ch = chop $str; print $str; ram print $ch; a chop removes and return the last character of the string. @names = (rama, sita , laxman); $ch = chop @names; print @names; ram sit laxma print $ch; n when is chop is applied to a list it removes last letter from each string but returns the character that is removed from last string. 2. chomp string-variable chomp list chomp The default variable for chomp is $_ Chomp removes last character from the string only if it is new line character. The return value is the integer value giving the number of elements that are actually removed. @names = (rama\n, sita , laxman\n); $n = chomp @names; print @names; rama sita laxman print $n; 2

PRACTICE MAKES MAN PERFECT .

Page 22

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

$name = <STDIN>; rama chomp $name; if ($name == rama) if ($name == rama\n) ----- after chomp (recommended) ----- without chomp

3. substr(string, offset,[length]) If the length is not specified it returns all the characters starting from offset till the end. $str = Hello Perl World; $str1 = substr($str , 6 , 4); print $str1; perl $str2 = substr($str,6); print $str2; no. of chars need not be same perl world substr($str,6,4) = DIGITAL; moidifying original string print $str; appended to string Hello DIGITAL world substr($str,16) = ABCD ; index of last char Hello perl world ABCD if greater than last index error occurs 4. index(string , substring) Search for substring within the string if found the index of first matched character is returned on success return index of 1st matched character on failure -1 is returned. $str = Hello perl world; $n = index($STR, perl); print $n; 6 5. rindex(string, substring) Searches for the last occurrence of the substring. 6. split(delimiter, string) Used to split a string into substrings based on delimiter Delimiter --------------------- character (or) reg exp $str = rama,sita,laxman,hari; @arr = split(,,$str); print @arr;

PRACTICE MAKES MAN PERFECT .

Page 23

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

rama sita laxman hari 7. join (delimiter,array) Joins the array elements into a string with the delimiter specified. $str1 = join(:,@arr); print $str1; rama:sita:laxman:hari 8. length(string) returns the number of characters in the string. print length(rama); 4 9. lc(string) Returns a copy of string converted to lower case. 10. uc(string) Returns a copy of string converted to upper case. 11. lcfirst(string) Returns a copy of string converting first character to lower case. 12. ucfirst(string) Returns a copy of string converting first character to upper case 13. ord(string) Returns the ASCII code of the first character of the string. print ord(Cat); 67 ord ordinal value 14. chr(ascii code) Returns the character corresponding to ASCII code. print chr(68); D 15. grep {pattern} list/array Used to search the pattern in each element of the list and return elements @lines = <STDIN> ---------------------------Ctrl+D @arr = grep {[pP]erl} @lines; Looping command for matching

PRACTICE MAKES MAN PERFECT .

Page 24

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

16. map {function} list/array Map executes the function for each element in the list & returns a list . @names = map {uc} @name; II. ARRAY functions: 1. push(array, element1,element2,element3,------) array as first element Used to append set of elements to the array The original array is size is modified and size is grown by the number of elements pushed. @arr = (10,20,30); push(@arr,40,50,60); If array is print @arr\n; not present 10 20 30 40 50 60 array is 2. unshift(array, element1,element2,element3,------) prepand the set of elements to the array @arr = (10,20,30); unshift(@arr,40,50,60); print @arr\n; 40 50 60 10 20 30 3. shift(array) Shift all the elements of the array to left by 1 position. The size of array is reduced by 1. Returns first element. @arr = (10,20,30); $n= shift(@arr); print $n; 10 4. pop(array) Removes an element from the end of the array. @arr = (10,20,30); $n= pop(@arr); print $n; 30

PRACTICE MAKES MAN PERFECT .

Page 25

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

5. splice(array,offset,length,[ element1,element2,element3,------]) Splice can insert or remove elements from the array. If the length is 0 then only insertion takes place. @arr = (5,8,10,20,30,40,50,60); splice(@arr,2,3,15,20,30,35,45); print @arr\n; 5 8 15 20 30 35 45 40 50 The above 5 functions affect the original array. 6. reverse(array) Reverse the order of the array and returns the array. Original array is not affected. @arr = (10,20,30); @rev = reverse(@arr); print @rev\n; 30 20 10 $str = HELLO; $str1 = scalar reverse $str; print $str1; OLLEH 7. sort [{Block}] LIST Sorts the elements of array (or) list and returns them. Original array is not affected. The default sort order is called as lexical & ascending. Lexical comparison starts from first character. Ex : ast r a ------ larger ast e rix Mismatched occurred at 4th char and
first word is larger.

astra -----larger Astra Comparison is case sensitive and based on ASCII code. The set of values given to character is called collating sequence. @copy = sort @names; ------lexical ascending @copy = sort {$a cmp $b} @names; ------lexical ascending

PRACTICE MAKES MAN PERFECT .

Page 26

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

@copy = sort {$b cmp $a} @names; ------lexical descending The sort does not directly work numbers. It just performs lexical sort on the numbers also. When 2 and 12 are to be sorted in ascending if we directly sort it sorts as if 12 < 2. For numbers : @copy = sort {$a <=> $b } @numbers ; ------ numeric ascending @copy = sort {$b <=> $a } @numbers ; ------ numeric descending Here $a and $b are predefined variables for sort operation.

III. Hash functions: 1. delete delete($age{ram}); Delete is used to delete a key value pair from the hash list. Original hash is affected. delete($arr[0]); sets $arr[0] to undef . 2. keys(hash variable) Scalar context returns number of keys. %ages = (ram => 20 , sita =>18 ,laxman =>19) $n = keys(%ages); --- 3 List context returns a list of all keys in the hash. @k = keys (%ages); Array of only keys Eg : foreach $var ( keys(%ages)) { print $var => $ages{$var}\n; } key value The above foreach loop is to print the key value pair. 3. values(hash variable) Same as keys but return values.

PRACTICE MAKES MAN PERFECT .

Page 27

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

In scalar context returns number of values. In list context returns a list of all values. 4. each(hash variable) Returns a list of key associated with value pair 1st element ----- key 2nd element ----- value Ex: while (($k, $v) = each (%ages)) { print $k => $v\n; } IV. Time functions: 1. time() Returns the time elapsed from 1.1.1970 00:00:00 and current time. 2. localtime() In scalar context returns a string containing the time & date for current time stamp. wed jun 20 14:05:30 2012 In list context returns an array containing the time and date values for current time. Seconds Mins Hrs Day of Month Day of Day ISDST month week of year 0-59 0-59 0-23 1-31 0-11 0-6 1-366 0 (or) 1
Jan Dec Day light saving time

localtime(no.of elapsed seconds from 1.1.1970 00:00:00) localtime(time() ); Default (implicit) $t = localtime(time()value)
After the current time Before the current time

$t = localtime(time() + 60*60*24*365) 3. gmtime() It is same as locatime but with reference to greenwhich mean time. V. Math functions: Function Usage abs(n) Absolute of n sqrt(n) Square root of n exp(n) Exponential of n log(n) Natural logarithm sin(n) Sine value , n should be in radians

PRACTICE MAKES MAN PERFECT .

Page 28

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

cos(n) int(n)
rand() rand(n)

Cosine value , n should be in radians Truncate the fractional part


--- generates a random number between 0 and 1 accuracy is upto 15 decimals. --- argument used to multiply the value by the number 0 and n

srand(seed_value) srand(10) --- used to generate pseudo random number sequence.

If we want to use complex numbers then use the module. use Math::Complex; $c1 = Math::Complex->new(-2,3); $c2 = Math::Complex->new(4,5); $c3 = $c1 * $c2; print ($c1 * $c2 = $c3\n); -2+3i * 4+5i = -23+2i Base conversion functions: $n = 10; = 012; = 0xA; = 0b1010; print $n; 10 $n = 012; = 0xA; = 0b1010;

By default stored with base 10

No conversion takes place stored asis

If we want to convert from any base to 10 then we want to use functions. hex($n); prefix 0x is optional base 16 numbers

converts hexadecimal to decimal print hex(0xA); / print hex(A); 10 Hex does not convert binary or octal numbers to decimal.

PRACTICE MAKES MAN PERFECT .

Page 29

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~ oct($n) converts octal/hex/binary to base 10. print oct (0xA); 10 print oct(0b1010); 10 print oct (12); 10 With prefix converts all three types & without prefix only octal. Decimal to Binary: Using pack unpack functions. $decimal = 4; $binary = unpack(B32,pack (N,$decimal)); print $binary; 00000000000000000000000000000100 Binary to decimal: $newdecimal = unpack(N,pack(B32,$binary)); print $newdecimal; 4 Formating functions: 1. printf(formatting string, value list) 2. sprintf( formatting string, value list) $str = sprintf(%d + %d = %d, $a,$b,$c); References : 1. Hard 2. Soft (Symbolic) Hard references stores the address of another variable. Soft reference stores the name of another variable. Hard references can be created to 1. 2. 3. 4. 5. 6. 7. Scalar Array Hash Another reference Sub routine List Constant value

-------

print to console instead of print to console return string

PRACTICE MAKES MAN PERFECT .

Page 30

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Reference to scalar: $x = 10; $r = \$x; print $r; SCALAR(1001) type address returns type of referent address of operator

print ref($r); SCALAR

$ prefix dereferencing operator print $$r; 10 $$r = 20 print $x; 20 $r2 =\$r; print $r2; REF(2001) print ref($r2) REF print $$r2; SCALAR(1001) print $$$r2; 20 $$$r2 =30 print $x; ------- reference to reference ------ modifying the referent value

PRACTICE MAKES MAN PERFECT .

Page 31

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~ 30 Reference to array: @arr = (10,20,30,40,50); $r1= \@arr; print $r1; ARRAY(1001) @ prefix dereferencing operator for array reference (more than one element) $ for single element print @$r1; 10 20 30 40 50 print @$r1[1..3]; 20 30 40 print $$r1[2]; 30 $$r1[2] = 28; or @$r1[1..3]=(25,35,45); @$r1 = (100,200,300); Array is modified $r1->[2] = 28; or print $r1->[2]; -> or $ infix prefix

$r2 = \$r1; print $r2; REF(2001); print $$r2; ARRAY (1001) print @{$$r2}; 100 200 300

PRACTICE MAKES MAN PERFECT .

Page 32

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~ print @{$$r2}[1,2] 200 300 print $$r2->[2]; 300 print $$r2[1]; 200

Reference to Hash: %ages = (ram , 20 , sita=>18,laxman=>19); $r =\%ages; print %$r1; ram20laxman19sita18 print $$r1{ram}; 20 print $r1->{ram}; 20 foreach $k (keys(%$r1)) { print $k => $$r1{$k}\n; } print @$r1{ram, sita}; $$r1{ram} = 25; @$r1 {ram , sita} = (25,35); %$r1 =( ); Overwrite the original hash

PRACTICE MAKES MAN PERFECT .

Page 33

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Reference to list : $a = 10; $b = 20; $c = 30; $r1 = \($a,$b,$c); $r1 = (\$a,\$b,\$c); @arr = \($a,$b,$c); --- creates array of references. Both are same

Reference to constant: $pi = \3.1415; print $pi; SCALAR(1001); print $$pi; 3.1415 $$pi = 3.14159; ---- not permitted Read only variable

Reference to sub: Sub routines are just like functions in c. Defining a sub : sub subroutine_name [(proto tye)] { set of statements ; return [value /list]; } list of types where sub can recieve

PRACTICE MAKES MAN PERFECT .

Page 34

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

(1) sub name { // can receive any number of arguments including 0 } (2) sub name ( ) { //no arguments can be received by subroutine } (3) sub name (PROTO) { //specify the type & number in proto } If return statement is missing the value of last statement is returned by default.

Calling a sub: message; message(); message(10,20,30); (&)message(hello,world); $r1=\&function; ..reference to sub & symbol is used for sub routine $r1->(10,20,30); $r1=\&message; $r1(10,20,30); &$r1(10,20,30);

Anonymous array: [ ] anonymous array composer Explicit : $r1 = [10,20,30,40,50]; print @$r1;

PRACTICE MAKES MAN PERFECT .

Page 35

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~ $aref = undef; @$aref = (100,200,300) ; @arr = ([100,200,300],[10,20,30],[40,50,60]); array of arrays / 2D arrays Anonymous Hash : (1) Explicit : {} $ages = {ram =>20,sita =>18,laxman =>19}; (2) Implicit : %$href =(mumbai,30,vizag,28);

Anonymous sub: $rs =sub { }

Soft /symbolic References : $x = 10; $r1 = x; soft reference to x

In soft reference the name of the variable is stored Print $$r1; 10 @arr = (10,20,30,40); $r2=arr; print @$r2; 10 20 30 40 %ages = ( ) $r3 = ages ; while (($k,$r)=each %$r3)

PRACTICE MAKES MAN PERFECT .

Page 36

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~ { print $k = $v \n; } pragma is a directive to compiler pragma use strict refs keyword subroutine will not allow to use the soft reference below this pragma enforces strict

//use module-name [list of routine]

Complex Data Structure: 1. 2. 3. 4. 5. Array of Arrays Hash of Arrays Array of Hashes Hash of Hash Combination

Array of Array: $r1 = [10, 20, 30] ; $r2 = [40, 50, 60]; $r3 = [70, 80, 90]; @arr = ($r1, $r2, $r3); array of references @ar1 = ([10, 20, 30] , [40, 50, 60] , [70, 80, 90]); $ar1[1] reference to second array print @$arr[1]\n; 40 50 60 print ${$ar[1]}[1]; print $arr[1]->[1]; print $arr[1][1]; 50 $arr[3] = [100, 110, 120]; $arr[1][3] = 65; $arr[1][3,4] = (65,68); foreach $r (@arr) {

PRACTICE MAKES MAN PERFECT .

Page 37

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~ print @$r\n; } Hash of Array : %marks = (s1=>[90, 80, 75], s2=>[80,,85, 90], s3=>[90, 95, 100]); $marks{s1} ref to index array print @{$marks{s1}}; 90 80 75 print ${$marks{s1}}[1] 80 print $marks{s1}->[1]; 80 while(($k,$v) = each (%marks)) { print $k => @v\n; } Array of Hashes: @arr = ( {rollno => 10, name => ram, age => 20}, {rollno =>11, name => sita, age =>18}, {rollno =>12, name => laxman, age =>19}); $arr[0] --- ref to hash %{$arr[0]} while(($k,$v) = each(%{$arr[0]})) { print $k => $v\n; } foreach $r (@arr) { while(($k,$v) = each(%{$arr[0]})) { print $k => $v\n; } print \n; } Hash of Hash: %student = ( s1=>{rollno => 10, name => ram, age => 20}, S2=>{rollno =>11, name => sita, age =>18},

PRACTICE MAKES MAN PERFECT .

Page 38

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~ S3=>{rollno =>12, name => laxman, age =>19}); print %{$student{s1}}; $ramref = $student{s1}; while(($k,$v) = each(%{$ramref})) { print $k => $v\n; } $student {s4} = { }; ---adding a hash

while(($k1,$v1) = each(%student)) { print $k1=> $v\n; while(($k,$v) = each(%{$v1})) { print $k => $v\n; } }

Subroutine: sub sub_name [(PROTO)] { Statements; [return [value/List]]; } Name sub_name sub_name( ) sub_name(PROTO) Proto No No Yes paranthesis No Yes Yes Arguments Any number of args No arguments Specified number of args

PROTO

-----

list of types

Required parameters ; optional parameters The required list and optional list are separated by ; . The order must be (required ; optional) Ex: ($$:$) may or may not be required

two scalars required To use the optional arguments we must have atleast one required argument. sub message

PRACTICE MAKES MAN PERFECT .

Page 39

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~ { print @_\n; } message (10, 20, 30, hello);

arguments are optional

predefined array @_ or @ARG which contains the arguments passed to a sub routine . to include or use @ARG we must use a module . use English; print @_\n: --all the arguments passed will be printed

sub message { print @_\n; $_[0] +=5; } message (10 , 20 , 30 , hello); $a = 10 ; $b = 20 ;$c = 30; message ($a , $b ,$c); print $a; 15 $ARG[0] or $_[0] is an alias to $a The arguments are passed by reference by default sub message { $x = $_[0]; $x += 5; } message ($a , $b ,$c,@arr,%ages); print $a; --does not changes as we are working on the copy Default arguments: sub findsum { $x = $_[0]; $y= $_[1]; $z=$_[2] || 30; $sum = $x + $y +$z; [return $sum;] } $ref = findsum(10,20);

default value for z

PRACTICE MAKES MAN PERFECT .

Page 40

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

60 default value i.e., $z=30 is considered $ref = findsum(100,200,300); 600 Named arguments: sub findpower { ($x,$y) = @_; return $x ** $y; } findpower(5,3); --5*5*5 =125

sub findpower { %myhash= @_; $b= $myhash{base} || 2; $b= $myhash{exp} || 2; return $b ** $e; } findpower(base,5,exp,3); findpower(base,5); findpower(exp,3); findpower; sub message { $x = 10; my $y = 20; local $z = 30; fun1(); } print $x; print $y; print $a; ----- 5*5*5 = 125 ----- 5*5 =25 ----- 2*2*2 = 8 ----- 2*2 = 4

global scope , scope is throughout the package

10 not accessible 100

PRACTICE MAKES MAN PERFECT .

Page 41

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~ The scope of a variable can be using my, local, our keywords. Scope of my --------- with in the braches Scope of local --------- through out the stack Scope of our --------- through out the file sub fun1 { print $x; print $y; print $a; }

10 undef 30

file1.pl package p1; $a = 10; my $b = 100; Accessed outside the package It can not be accessed outside the package , this is private to package

File2.pl package p2; require file1.pl; print $p1:a; print $p1:b; -- not accessible

File3.pl package p3; our $c = 10; my $b = 100; package p4; print $c; ---- valid $c is our

Pragma : use strict vars ; --- prevents creation of global variables outside user defined package

$x = 10;

----

not valid

PRACTICE MAKES MAN PERFECT .

Page 42

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

my $x = 10 ; ---package p1; $y = 10; ----

valid

valid

Declaration of subroutine: sub name (PROTO); 1. sub_name args declaration called statement Definition 2. If the calling statement uses parenthesis then no need of declaration. sub_name (args) ----not require declaration Definition called statement
No declaration is required

Pass arguments by reference:sub message ($) { $r = $_[0]; $$r = 20; } $a = 10; message (\$a); print $a; 20 For scalar Proto ($) (\$) or message ($a); or (\$)

PRACTICE MAKES MAN PERFECT .

Page 43

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Argument For arrays Proto Argument For hashes Proto Argument

(\$)

($)

($) (\@)

(\@) ($) (@arr) (@arr)

($) (\%)

(\%) (%)

sub message ($$) { } message (\%ages,\@arr);

Returning values from su: Wantarray --- to return different values based on the context use wantarray. wantarray return true when the context is list false but defined in scalar context false undefined in void context @arr = (40,50,10,20,30); sub mysub1(@) { if (wantarray) { return sort {$b <=> $a } @_;

PRACTICE MAKES MAN PERFECT .

Page 44

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

} elsif (defined wantarray) { my $sum = 0; foreach $ele (@_) { $sum += $ele; } return $sum; } else { print @_\n; return; } }
Array sorted in ascending order Return sum

@num = mysub1(@arr); $n = mysub1(@arr); --mysub1(@arr);


Print array elements

Caller: Provides information about calling subroutine to the called sub caller [level] stack level integer value returns a list

PRACTICE MAKES MAN PERFECT .

Page 45

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Information returned by caller 1. 2. 3. 4. Package name Filename Line number Subroutine name

sub mysub1 { print caller [0]; print caller 1; print caller 2; } sub mysub2 { print caller 1; mysub1; } sub mysub3 { mysub2; } mysub3;
Stack keeps on changing only one function is called at a time stack

-------

mysub1 mysub2 mysub3

---

mysub3

mysub1 mysub2 mysub3

caller

sub message($$$$) { } message (10, 20, 30); --error less number of argumnets

PRACTICE MAKES MAN PERFECT .

Page 46

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

&message (10, 20, 30);

--- no error

When & is used proto validation is not done Guideline: proto validation is done when & is not used , so avoid using of & when proto need to be validated. sub message { print @_\n; } @_ = (10, 20, 30); &message; &message(10, 20, 30); message; -do not pass anything
Same

message (@_);

{ mycount =0; sub message { my $x =0; $count++; print $count; $x++; print $x; } }

PRACTICE MAKES MAN PERFECT .

Page 47

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Library files: Files with pm (or) pl extension


Cube.pl #!/usr/bin/perl sub findcube ($) { $n = $_[0]; return $n**3; } [return] 1; optional testcube.pl #!/usr/bin/perl require cube.pl; $a = <STDIN>; $res = findcube($a); print cube of $a = $res\n; Library file should have last line return 1 statement cube.pm #!/usr/bin/perl package cube; sub findcube ($) { return $_[0]**3; } [return] 1; testcube.pl For internal system understanding

For pm files .pm must have a package Package name should be same as name of file Constructor: This are sub routines with the predefined name BEGIN (uppercase only)

#!/usr/bin/perl require cube.pm; $a = <STDIN>; $res = cube::findcube($a); print cube of $a = $res\n;

PRACTICE MAKES MAN PERFECT .

Page 48

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

[sub] BEGIN { optional

Constructors are used to control what should be available to user with that library. more than one constructor in a single .pm file Constructor runs when it encounters use (or) requires statements in the program. BEGIN { use Exporter; @ISA = qw(Exporter); $text = Hello;
Directly imported d package cube; BEGIN { } sub findcube ($) { } [return] 1; cube.pm #!/usr/bin/perl

@EXPORT = qw(findcube, $text, routine1); @EXPORT_OK = qw(routine2,routine3); @EXPORT_FAIL = qw (routine6);


Quote words testcube.pl #!/usr/bin/perl require cube.pm; (or) use cube; $a = <STDIN>; $res = cube::findcube($a); print cube of $a = $res\n;

Prevent export of routine outside the module

If require statement is used then we cannot call the subroutine from other files. Destructor: Destructors are used to free system resources that the script using. sub END { destructor } automatically invoked when client program completes

There can be more than one destructor .

If more than 1 destructor then they will be executed in bottom up approach.

PRACTICE MAKES MAN PERFECT .

Page 49

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Nested modules: sub modules defined in another module 1. Create a top level module 2. Create a directory with that name. In the example shown, mod1 is the top level and mod2 is under that module , mod3 is under mod2. scope resolution operator
~

mod1.pm package mod1;

mod1

mod2.pm package mod1::mod2;

mod2 mod2.pm package mod1::mod2::mod3;

Standard modules: Path : /usr/bin/perl/5.8.5 shell module allows to use shell commands into the perl script Ex: use shell; $text = ls (-l dir1); Command options & arguments

$text1 = cat (~/dir1/file1.txt); print $text;


cpan.org for additional modules

use FILE::COPY; $x = copy (source, target); Returns no of files copied successfully

PRACTICE MAKES MAN PERFECT .

Page 50

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

FILES File handle ---just like file pointer in c

unique identifier that link to a file when it is opened STDIN STDOUT STDERR ------- reading from keyboard
Write to monitor or terminal

Opening of a file is done using a open function open (file handle , mode, filename); open (file handle, mode filename);
Use uppercase for file handle Two different versions Return true when file is opened successfully false otherwise

open(FH1, <file1.txt) || die (cannot open file);


It automatically calls the exit function to exit from file

unless(open(FH1, <file1.txt)) {

print cannot open file\n; exit 1; } Open mode C language R W A r+ w+ a+ Perl < > >> <+ >+ >>+ Read mode Write Append Read plus Write plus Append plus
Page 51

PRACTICE MAKES MAN PERFECT .

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

open (FH2, >file2.txt); print FH2 This is line1; print FH2 This is line2; print Enter few lines & quit on a independent line to exit; while ($line =<>) { last if ($line eq quit\n); print FH2 $line; } close (FH2);

open (FH3, <file3.txt); while ($line=<FH3>) { print $line; } close (FH3);

seek :

No. of bytes 0 -- SEEK_SET 1 -- SEEK_CUR 2 -- SEEK_END

seek(file handle , offset , location) seek (FH1,0,0); $tell = tell(filehandle)

tell is the command which give the position of file pointer.

There are two other modes command in file mode

PRACTICE MAKES MAN PERFECT .

Page 52

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

7th mode open (FH4, command | ) ----reading the output of the command

command & arguments

open (FH4, sort myfile | ); while($line = <FH4>) { print $line; } 8th mode open (FH5, | command); ---- writing the i/p to command

open (FH5, | tr [a-z] [A-Z]); print FH5 hello world\n; HELLO WORLD print FH5 welcome to veda; close FH5; open (FH6, | tr [a-z] [A-Z] > fileA.txt) redirecting output to a file

Binary files:

enum flag

sysopen (file handle, filename , mode , [permission]) octal value , eg. 0644 To use binary files we must include Fcntl i.e., use Fcntl;

PRACTICE MAKES MAN PERFECT .

Page 53

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

O_RDONLY O_WRONLY O_RDWR O_TRUNC O_CREAT O_BINARY O_APPEND

Open in read only mode Open in write only mode Read & write mode To erase the data qhile writing a file To create a new file Binary files For append mode

$! is a prefined variable that stores the system defined error automatically when open is not successful. To come out of script sysopen (filehandle, filename, name , [permission]) || die ($!) warn () syswrite(filehandle, buffer, max_number of bytes, [offset]); variable index to continue in script

The function returns the actual number of bytes written to file $n = syswrite(filehandle, buffer, max_number of bytes, [offset]); Offset is the starting index within the buffer, instead of reading from first byte we are reading from the specified byte. The function returns the actual number of bytes read to file. Binary file can store either text or image or sound or video clip. To close binary file use close function. Ex: sysopen(FH1, myfile1,O_WRONLY|O_BINARY|O_TRUNC|O_CREAT); $n = syswrite(FH1,$str,1024); Close(FH1); sysclose(FH1); default value for offset is 0 sysopen(FH2, myfile , O_RDONLY| O_BINARY); $n = sysread(FH2,$str2,1024); only one works

PRACTICE MAKES MAN PERFECT .

Page 54

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

print $n; close FH2; sysopen(FH3, myfile2, O_RDWR|O_TRUNC|O_CREAT|O_BINARY); $n = syswrite(FH3,$str2,1024); print $n; seek (FH3, 0,0); sysseek(FH3,0,0); any one works

$n 1= sysread(FH3,$str2,1024); print $n1;

Copy an image: sysopen (FH1, image1.jpg , O_RDONLY | O_BINARY); sysopen (FH2, image2.jpg , O_WRONLY|O_TRUNC|O_CREAT | O_BINARY); while($n = sysread(FH1, $buf , 1024)) { Syswrite(FH2, $buf, $n); } sysclose FH1; sysclose FH2;

Commands: rename to rename a file rename oldfile newfile; unlink deletes a file unlink filenames

PRACTICE MAKES MAN PERFECT .

Page 55

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

link to create hard link link target linkname; symlink target linkname; chmod to change file permissions chmod permissions file/directory octal value system (command options arguments); system(ls -l); --control back to script --- to create soft links

exec (ls -l) ; ---- control does not return to script

$x = `ls l dir1`; print $x; mkdir dirname [permissions] ---chdir dirname; rmdir dirname ; ------to create a new directory change directory remove directory

Directory handle: opendir directoryhandle directoryname; opendir (DH1, mydir) || die ( ); @contents = readdir(DH1); foreach $element (@contents) { if (-f mydir/$element) { print $element is file;

PRACTICE MAKES MAN PERFECT .

Page 56

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

} else if (-d mydir/$element) { print $element is directory; } }

closedir (DH1); rewinddir (DH1); telldir(DH1);

PRACTICE MAKES MAN PERFECT .

Page 57

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Regular Expression Sequence of characters used to represent a set of patters. Generally enclosed in a pair of / / /sequence/ default delimiters 2 types of characters 1.character literals 2.characters from regular expression language /perl/ Only 1 pattern /ab+/ => ab abb abbb. patterns

Binding operators: [string =~ ] regular expression operator [$_ =~] regular exp operator default 3 types of regular expression operators 1. Match operator 2. Substitute operator 3. Transliteration operator m// s/// tr///

Match : m/pattern/ or /pattern/ optional --- if delimiter are / / special character as delimiter m#pattern# m{pattern} m!pattern! $t = $str =~ /pattern/; true or false

PRACTICE MAKES MAN PERFECT .

Page 58

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

@match = $str =~ /pattern/g; Match operator does not modify original string $ | $&| $` $str =~ This is a perl string in a practice perl program using perl regexp; (1) (2) (3) $t = $str = ~/perl/ Scalar context $t = $str =~ /perl/g; true or false

When we dont use g the cursor position is reset to another search else cursor remains in the same position. print POS ($str); POS gives the position of search at next occurance @matches = $str =~ /perl/g; list context print @matches\n; perl perl perl use English; 1. $& $MATCH 2. $` $PREMATCH 3. $ $POSTMATCH print $` $& $; while ($str =~ /perl/gi) { print Matched text : $&\n; print Prematched text : $`\n; print Matched index : length ($`)\n; print starting index for next search : POS($str)\n; } contains matched string contains text before matched string contains text after matched string

PRACTICE MAKES MAN PERFECT .

Page 59

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

$str =~ /p.+l/g $str =~ /p.+?l/g

starting p to last l starting p to first l

Regular expression language: 1. . Anyone character except newline 2. Meta symbols: \d Any one digit \D Any one non digit \s Any one white space character (\t,\n,etc) \S Any one non white space character \w Any one perl word char (A-Z,a-z,0-9,_) \W Any one non perl word char 3. Character class [apoz] - any 1 character in the list [a-z] [^a-z] any 1 char not in the list Complement list 4. Escape sequence \t,\n\v, translate escapes \u,\U,\l , \L,\E 5. Alternate choice /$str1 | $str2 |$str3/ Quantifiers : Greedy: * + ? {n} {n,m} {n, }

Repeat previous char 0 or more times Repeat previous char 1 or more times Repeat previous char 0 or 1 time Exactly n times Previous char between n & m times Previous char atleast n time

$digit = 123456789; while ($digit =~ /\d{3,5}/g) { print $&\n; } Non greedy : *? , +? , ??, {n}?, {n,m} ? , {n, } ?

output 12345 6789

PRACTICE MAKES MAN PERFECT .

Page 60

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Anchors : They are special characters , they specify position of the pattern in the string 1. ^ /^pattern/ beginning of the string 2. $ /pattern$/ ending of the string /m pattern modifier (1) $str =~/^perl/gm at the beginning of each line in the string $str =~ This is foo and \n bar; $t =$str =~ /^bar/gm; true \A ^ both are same $t = $str =~ /\Abar/gm Does not account for m (2) $ & \Z are same /pattern$/ --- ending of the string $str =~ /pattern$/gm \Z also does not account for /m $str =~ /pattern\z/m \z accounts for /m (3) \b ---- perl word boundary \B ---- perl non word boundary /\bpattern/ /pattern\b/ /\bpattern\b/ 1 2 3 $str = Unlike bigcat this cat eat catterpiller; $str =~ /cat/g $str =~ /\bcat/g $str =~ /cat\b/g $str =~ /\bcat\b/g --------matches 1, 2, 3 matches 2,3 matches 1,2 matches 2

PRACTICE MAKES MAN PERFECT .

Page 61

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Grouping & Back referencing: $date = 04-07-2012; $date =~ /(\d+)-(\d+)-(\d+)/; $1 $2 $3 \1 \2 \3 --Default variables

only inside the same pattern

if ($date =~ /(\d+)-(\d+)-(\d+)/) { print American format $2-$1-$3 ; print Japanese format $3-$2-$1; } Back tracking is done only when complete pattern is matched , else the matched part is discarded. Pattern modifier: \g global \i ignore case \m check each new line \s allow the . to match newline \x allow including white spaces and comments in pattern \o option to improve the performance \cg continue global $str = This is foo and \n bar\n; $str =~ /foo.+bar/; --- false $str =~ /foo.+bar/s; --- true $date =~ m{(\d+)- # day (\d+)- #month (\d+) #year}x; quote regular expression $rex = qr (regular exp); qr (m{{(\d+)- # day ignored while searching pattern

PRACTICE MAKES MAN PERFECT .

Page 62

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

(\d+)- #month (\d+) #year}x }); $date =~ /$rex/ --- to store regular exp in a variable & use it many times $str = This is to teach a perl program in perl class using perl regular expression with customized teaching. while($str =~ /perl/gc); while ($str =~/perl/gc) { cancel resetting to the beginning print . } print POS($str); while ($str =~ /teach/g) --only one occurrence of teach i.e., last teach in teaching { } /c --- pattern modifier always occurs along with g $str = <img src= file1.jpg width = 100 height = 500 > <\img>; if ($str =~/<(img|a).*>[\s\w.]*</\1>) { print found <$1> tag\n; }

S/// -- substitution : $str =~ s/perl/unix/ Pattern substitution string/ Replacement string

This searches for the occurrence of the pattern and if found it is replaced with replacement string. If no match occurs no substitution.

PRACTICE MAKES MAN PERFECT .

Page 63

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

$n = $str =~ s/perl/unix/g Number of substitutions that are actually taken place search for multiple occurrences

It modifies the original string , so we must work on a copy . ($copy = $str) =~ s/perl/unix/g All the pattern modifiers that are used with match operator can be used along with substitution operator except cg Another modifier e used with substitution , evaluates the replacement string prior to substitution. $str = This prog was compile on DATE and should be used only after DATE; $str =~ s/DATE/locattime/g; $str =~ s/DATE/locattime/ge; -- simply replaces DATE with localtime -- substitutes DATE with current time.

$str =~ s/(\w+)/\U$1/ge; --- converts lower case to upper case

Transliteration :

$str =~ tr/ABCD/EFGH/; search characters

by default global without g

replacement characters ignored in void context

$str =~ tr/ABC/EFGH/;

$str =~ tr/ABCD/EFG/; Perl remembers the most recent replacement character

PRACTICE MAKES MAN PERFECT .

Page 64

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

$str =~ tr/ABCD/DEFG/; Perl search engine will not pass once replaced characters for searching. $str =~ tr/ABCD/EFG/d; delete search character that does not have any replacement char pattern modifier for tr: d -deleting c -Complementing search chars s -squeeze multiple adjacent characters that are same, to a single character $str = This is my cat; $str =~ tr/a-zA-Z/-/c; This-is-my-cat $str = foooooodoooooboooo; $str =~ tr/a-z/a-z/s; fodobo Replaced characters are rechecked for the adjacent similar character. $str =~ tr/a-z/A-Z/; Assertions: 1. Look-Ahead 2. Look-Behind i. Positive look ahead assertion /pattern (?= Expr)/ Condition search It searches for the pattern & if the expression found after the pattern then only search will be true else false . $str = foo is followed by bar in foobar; 1 3 2 4 --- converting lower case to upper

PRACTICE MAKES MAN PERFECT .

Page 65

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

while ($str =~ /foo(?=bar)/g) { print (foo is found before bare); print $&; } ii. Negative look ahead assertion /pattern (?!EXPR))/ Positive look behind assertion /(?<=EXPR)pattern/ Negative look behind assertion /(?<!EXPR) pattern/ fixed string /(?=EXPR)/ ---

foo 2 is matched

iii. iv.

zero width look ahead

$digit = 123456789; while($digit =~ /(?=(\d{3}))/g) { print $1, -; } 123-234-456-567-678-789 while($digit =~ /(\d{3}))/g) { print $1, -; } 123-456-789 Special coding in perl:
myscript.pl while ($line = <STDIN>) { print $line ; ctrl+d } while (<>) {

for this #!/usr/bin/perl -n #!/usr/bin/perl -p

- Same }

print ; ctrl+d

PRACTICE MAKES MAN PERFECT .

Page 66

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

Short code command line : perl ne print file1.txt perl myscript.pl file1.txt file2.txt contents are read & placed inside while loop perl i pe s/unix/perl/g file1.txt inplace moifiaction of file Perl -i.bak pe s/unix/perl/g file1.txt
Backup file : file1.txt.bak is created with the content of original file

if ($_ =~ /perl/) { print ; }

- sameprint if /perl/;

while (<>) { if ($.==25) { } }

Line numbers from current file

if(10..20) { print ; }

while (<>) { if (/pattern1/../pattern2/) { print ; } }

if both patterns are found on same line one line is printed

PRACTICE MAKES MAN PERFECT .

Page 67

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

while (<>) { if (/pattern1/.../pattern2/) { print ; } } $. stores the current line number $ARGV stores the current file name @ARGV stores command line arguments @ARG , @_ stores arguments to sub routine

if both patterns are found on same line pattern 2 is not recognised

PRACTICE MAKES MAN PERFECT .

Page 68

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

PRACTICE MAKES MAN PERFECT .

Page 69

~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~PERL ~ PERL ~ PERL ~ PERL ~ PERL ~

PRACTICE MAKES MAN PERFECT .

Page 70

S-ar putea să vă placă și