PERL (Practical Extraction Report language)
- Perl is developed by "Larry Wall" in 1986.
- The home of the Perl is Unix
- Perl is written in "C" language.
- Perl is interpreter based language.
- Perl is a case sensitive scripting language.
Differences between Scripting Language and Programming Language
Scripting Language
Programming Language
The perl borrowed many features from Unix utilities (like awk, sed, grep, tr ) and added "C" language functionality.
The features of Perl
- System Administration
- Database Administration
- Web Development (CGI)
- Networking (Net)
- Bioinformatics (Bio)
- Testing (Test)
- VLSI
- Telecom
- GUI development
- Single line comment (#)
- Multi line comment
=pod (plan old documentation)
------------------
------------------
------------------
=cut
How to run Perl programs on windows platform
How to run Perl programs on Linux platform
$perl program.pl
$chmod a+x program.pl
$./program.pl
How to see location of the Perl?
$which perl ß
/usr/bin/perl
How to see the help in Linux?
$man perl
How to see the version of the perl?
$perl –v
Write a program to print welcome message?
#!/usr/bin/perl -w
#Author: Pavankumar
# -w displays warnings
print "welcome to SEI \n";
print "This is my first perl program \n";
Variable
- Scalar variables
- Array variables or Indexed array variables
- Hash array variables or Associated array variables
Scalar variables
Array variables
Hash array variables
Print:
"print" is a predefined function and it is used for to write data to the output screen.
Ex: print ("Hello");
print "Hello";
print STDOUT "Hello";
#hello.pl
#!/usr/bin/perl -w
print ("hello, perl\n");
print "hello, perl\n";
print STDOUT "hello, perl\n";
The standard input/output/error buffers are
- STDIN
- STDOUT
- STDERR
<STDIN> is the standard input handler used to take input from user.
<STDOUT> is the standard output handler used to write data to the screen.
<STDERROR> is the standard error handler used to write errors.
#Write a program to accept the name and display
#prg2-chomp.pl
#!/usr/bin/perl -w
print "Enter a name:";
$name=<STDIN>; #<> -- Diamond operator
chomp($name);
print "Hello, $name, How are you?\n";
print "Enter a name:";
chomp($name=<STDIN>);
print "Hello $name, How are you?\n";
print "Enter a name:";
chomp($name=<>); # By default it reads input from the keyboard
print "Hello $name, How are you?\n";
Note:
"chomp" is a predefined function, it deletes the given string last character, if it is new line character
Scalar variable Examples
$a=100; # integer
$b=10.5; # float
$course="perl"; # String
$name=’Tecno soft’; #String
$k="100"; # String
$m="25.67"; #String
#prg-scalar.pl
#!/usr/bin/perl -w
$a=100; # integer
$b=10.5; # float
$course="perl"; # String
$name='Tecno soft'; #String
$k="100"; # String
$m="25.67"; #String
print "a=$a, b=$b, course=$course, name=$name, k=$k, m=$m\n";
Strings are classified into 3 types
Double quoted strings (" ") qq// or qq{} or qq() or qq<> or qq[]
Single quoted string (‘ ‘) q// or q{} or q() or q<> or q[]
Back quoted strings or Back tick strings (` `) qx// or qx{} or qx() or qx<> or qx[]
Ex1:
$str="perl";
$x="I like $str";
print $x;
Ex2:
$str="perl";
$x=’I like $str’;
print $x;
Ex3:
$str="perl";
$x="I like \n $str";
print $x;
Ex4:
$str="perl";
$x=’I like \n $str";
print $x;
Note:
In double quoted strings, variable substitution takes place but in single quoted strings, every thing it treats as normal text.
$str = "I said, "Don’t write to dist""; -- Incorrect
$str = "I said, \"Don’t write to disk\"’; -- Correct
$str = ‘I said, "Don\’t write to disk"’; -- Correct
#!/usr/bin/perl -w
$x = "disk";
$str = qq/I said, "Don’t write to $x"\n/;
print $str;
Output:
I said, "Don’t write to disk
#!/usr/bin/perl -w
$x = "disk";
$str = "q/I said, "Don’t write to $x"\n/;
print $str;
Output:
I said, "Don’t write to $x\n"
Back quote (``): It is used to execute operating system commands.
#!/usr/bin/perl -w
$x=`ls -lrt`;
print $x;
#!/usr/bin/perl -w
$x=qx/who/;
print $x;
Operators:
Arithmetic operators
: + - * / % **
Ex1:
$a=10;
$b=4;
print $a+$b; #14
Ex2:
$a=10;
$b="25abc";
print $a+$b; #35
Ex3:
$a=10;
$b="abc25";
print $a+$b; #10
Ex4:
$a="Hello";
$b="Pavan";
print $a+$b; #0
Ex5:
$a=10;
$b="456abc";
print $a+$b; #466
Ex6:
$a=10;
$b="25abc";
print $a+$b; #35
print $a.$b; #1025abc
Ex7:
$a=2
$a=2
$b=4
print $a**$b; #2**4=16
Relation operators:
a) Numeric comparison operators
: <, >, <=, >=, = =, ! =, <=> (Three way comparison operator)
b) String comparison operators:
lt, gt, le, ge, eq, ne, cmp (Three way comparison operator)
Ex1:
$a=100;
$b=20;
$a>$b ---- True
$a gt $b ---- False
Ex2:
$x ="hello";
$y ="pavan";
$x gt $y --- True
$x > $y --- False
Ex3:
$c = $a <=> $b;
If a>b à 1
a<b à -1
a= =b à 0
Ex4:
$k = $x cmp $y
If x>y à 1
x<y à -1
x= =y à 0
Logical operators:
&&, ||, ! or and, or, not
Sting multiplication operator:
x
$str = "perl";
$k = $str x 5; # It multiplies str by 5 times
print $k; # perlperlperlperlperl
String concatenation operator:
$str1 = "SEI";
$str2 = "Investments";
a) $k = $str1.$str2;
print $k; #SEIInvestments
b) $k = $str1." ".$str2;
print $k; #SEI Investments
Range operator:
1..10 ----- Correct
a..z ------ Correct
-10..-1 ---- Correct
10..1 ---- Incorrect
z..a ----- Incorrect
-1..-10 ---- Incorrect
print 1..10 # It prints no’s 1 to 10
Assignment operators:
$a = 10;
$b = 20;
$c = 30;
Or ($a,$b,$c)=(10,20,30)
Short hand assignment operator:
+=, -=, *=, !=, %=, .=, x=
Ex:
- $a=10;
- $str="load";
$a=$a+5; (or) $a+=5;
$str=$str."ing"; (or) $str.="ing";
Increment operator: ++
$a = 10;
$a = $a+1; (or) $a+=1; (or) $a++;
Decrement operator: --
$a = 10;
$a = $a-1; (or) $a-=1; (or) $a--;
IF Statements:
- Simple if
- simple unless
- if….else
- unless…else
- if…elseif…
- single line if statement
- Single line unless statement
if(condition)
{
------------
------------
}
-------------
-------------
unless(condition)
{
-------------
-------------
}
-------------
-------------
if(condition)
{
------------
------------
}
else
{
-----------
-----------
}
-----------
-----------
unless(condition)
{
------------
------------
}
else
{
------------
------------
}
--------------
--------------
if(condition)
{
------------
------------
}
elsif(condition)
{
-------------
-------------
}
else
{
------------
------------
}
statement1 if(condition);
---------------
---------------
Statement1 unless(condition);
------------------
------------------
Looping statements:
- while loop
while(condition)
{
-----------
-----------
}
---------
---------
until(condition)
{
-----------
-----------
}
-----------
-----------
do
{
-----------
-----------
}
while(condition);
do
{
-----------
-----------
}
while(condition);
------------
------------
for(initialization;condition;incr/decr)
{
---------------
---------------
}
--------------
--------------
foreach variable(list of values)
{
--------------
--------------
}
------------
------------
last :
next:
It is used for to start the loop again.
while(condition)
{
------------
------------
last;
------------
------------
}
-----------
-----------
while(condition)
{
-------------
-------------
next;
-------------
-------------
}
-------------
-------------
Programs on if statements:
#write a program to accept a number and check the no is an even or odd?
#!/usr/bin/perl -w
print "\nEnter number:";
chomp($n=<STDIN>);
if($n%2==0)
{
print "\n$n is an Even no\n";
}
else
{
print "\n$n is an Odd no\n";
}
#WAP Accept a number and check the no is 3 digit no or not?
#!/usr/bin/perl -w
print "\nEnter a number:";
chomp($n=<STDIN>);
if($n>=100&&$n<=999)
{
print "\n$n is a 3 digit number\n";
}
else
{
print "\n$n is not a 3 digit number\n";
}
#WAP to accept username and password and check the user is valid or not?
#!/usr/bin/perl -w
print "\nEnter Username:";
chomp($username=<STDIN>);
print "\nEnter Password:";
chomp($password=<STDIN>);
if($username eq "pbandaru" && $password eq "pbandaru")
{
print "\nWelcome to SEI\n";
}
else
{
print "\nInvalid username or password\n";
}
#WAP to accept 2 strings and check string1 >string2 or string1<string2 or both strings are equal?
#!/usr/bin/perl -w
print "\nEnter a string1:";
chomp($str1=<STDIN>);
print "\nEnter a string2:";
chomp($str2=<STDIN>);
$x=($str1 cmp $str2);
if($x = =1)
{
print "\n$str1 is greater than $str2\n";
}
elsif($x = =-1)
{
print "\n$str1 is less than $str2\n";
}
elsif($x = =0)
{
print "\nboth are equal\n";
}
#WAP to check whether variable exist or not?
#!/usr/bin/perl -w
$a=10;
undef($a); #undef function is used for to delete a variable
if(defined($a)) #defined function returns true, if the variable defined otherwise false
{
print "variable exist\n";
}
else
{
print "No such variable\n";
}
Looping Statements:
#WAP to print numbers from 1 to 10
#!/usr/bin/perl -w
$i=1;
while($i<=10)
{
print "$i\t";
$i++;
}
print "\n\n\n";
for($i=1;$i<=10;$i++)
{
print "$i\t";
}
print "\n\n\n";
foreach $i (1..10)
{
print "$i\t"
}
print "\n\n\n";
foreach (1..10)
{
print "$_\t"; #$_ is a special variable which stores the default values
}
print "\n";
Arrays:
Syntax: @array_variable=(list of scalars);
Ex: @num=(10,20,30,40,50,60);
@x=(10,’perl’,4.5,60,"unix");
@days=("sun","mon","tue","wed",’thu","fri","sat");
@days=qw(sun mon tue wed thu fri sat);
Accessing array elements
print "@num"; #10 20 30 40 50 60 à With space
print @num; #102030405060 à Without space
print $num[2]; #30 à Prints third element
print "@num[1..4]";#20 30 40 50 à Prints elements 1 to 4
print "$num[-1]"; #60 à It prints the last element
print "@num[0,1,-1,-2]";10 20 60 50 à More than one element array representation
EX:
#!/usr/bin/perl -w
@num=(10,20,30,40,50,60);
print "@num"; #10 20 30 40 50 60 With space
print "\n";
print @num; #102030405060 Without space
print "\n";
print $num[2]; #30 Prints third element
print "\n";
print "@num[1..4]"; #20 30 40 50 Prints elements 1 to 4
print "\n";
print "$num[-1]"; #60 It prints the last element
print "\n";
print "@num[0,1,-1,-2]"; #10 20 60 50 More than one element array representation
print "\n";
Writing elements to array
$num[6]=70;
$num[3]=100;
@num[7..10]=(100,200,300,400); # It overwrites if it exists, if not creates.
$num[100]="abc"; # If the last index is 50 then it creates remaining indexes before 100.
EX:
#!/usr/bin/perl
@num=(10,20,30,40,50,60);
$num[6]=70; # It will create a new index and add an element
print $num[6];
print "\n";
$num[3]=100; # It will overwrite the existing element
print $num[3];
print "\n";
@num[7..10]=(100,200,300,400);
print "@num";
print "\n";
$num[100]="abc";
print "$num[100]";
print "\n";
$#array:
It returns the last index of the array.
EX:
#!/usr/bin/perl -w
@num=(10,20,30,40,50,60);
print "\nnum array last index is: $#num"; #5
print "\nTotal elements in num array is:",$#num+1; #6
print "\n";
$num[$#num+1]="hello";
@k=@num; #copying array
print "Copied array elements are:@k";
print "\n";
$n=@num; #Assigining lenth of the array
print "Length of the array is:$n"; #7
print "\n\n";
EX:
#!/usr/bin/perl -w
@x=(10,20,30,40,50,60);
$i=0;
while($i<=$#x)
{
print "$x[$i]\n";
$i++;
}
print "\n";
@y=(10,20,30,40,50,60);
for($i=0;$i<=$#y;$i++)
{
print "$y[$i]\n";
}
print "\n";
@z=(10,20,30,40,50,60);
foreach (@z)
{
print "$_\n";
}
print "\n";
EX:
#!/usr/bin/perl -w
print "Enter elements to store into array at end press ctl+d:";
chomp(@a=<STDIN>);
print "Entered elements are\n";
foreach $x (@a)
{
print "$x \n";
}
print "\n Total no of elements:",$#a+1;
print "\n";
EX:
#!/usr/bin/perl -w
#Accept n integer elements and store into array and find sum and display
print "Enter no of elements:";
chomp($n=<STDIN>);
$i=0;
$total=0;
while($i<$n)
{
print "\n Enter number:",$i+1,":";
chomp($a[$i]=<STDIN>);
$total=$total+$a[$i];
$i++;
}
print "\n given elements are:\n";
print "@a\n";
print "\nSum of above elements:$total";
print "\n"
Hash Array Variable:
It is a group of key pair values
It should begin with % symbol
%variable = (list of key pairs)
Examples
%names=("hari",10000,"venkat",9500,"neeraja",8000,"sai",9800);
%name=("hari"=>10000,"venkat"=>9500,"neeraja"=>8000,"sai"=>9800);
%cities=("ap"=>"hyd","tn",=>"chennai","kn"=>"bangalore");
Hash Array Functions:
Keys:
It returns the given hash array keys
keys%hasharrayname;
eg: keys%cities
output: ap tn kn
Values:
It returns the given hash array values
values%hasharrayname;
eg: values%cities
output: hyd chennai bangalore
each:
It returns the given hash array one key pair value
each%hasharrayname
eg: each%cities
output: tn chennai
exists:
It returns true if the given key exist in the given array
exists%hasharrayname
delete:
It deletes the given key pair from the given hash array
delete $hasharrayname{key};
eg: delete $cities{m};
Ex: print-hash-array-element.pl
#!/usr/bin/perl -w
%names=("anu"=>4000,"madhu"=>8000,"latha"=>3000,"hari"=>9000,"babu"=>5000,"balu"=>4000,"anu"=>2000);
foreach $x (keys%names)
{
print "\n$x salary is: $names{$x}\n";
}
print "\n";
EX: print-hash-array-element1.pl
#!/usr/bin/perl -w
%names=("anu"=>4000,"madhu"=>8000,"latha"=>3000,"hari"=>9000,"babu"=>5000,"balu"=>4000,"anu"=>2000);
while(($x,$y)=(each%names))
{
print "\n$x salary is: $y\n";
}
$x=keys%names;
print "\n";
print "total no of variables:$x";
print "\n";
File Handling:
File:
It is collection of data or group of records
The following are functions to handle files
open():
It is used for to create a new file or to open an existing file or to append data to the existing files.
open(FILEHANDLE,"mode Filename");
FILEHANDLE is a user defined name
Modes are classified into 3 types
- read mode (<) – Default mode
- write mode (>)
- append mode (>>)
How to open a file
Syn: open(FILEHANDLE,"<filename");
Ex: open(FH,"<sample.txt");
Note: In read mode if the given file exists, it opens a file and places a file pointer at the beginning of the file and returns true. If the file doesn’t exist, it fails to open file and returns false.
How to create a file
Syn:open(FILEHANDLE,">filename");
Ex: open(FH,">sample.txt");
Note: In write mode if the given file exists, it opens a file and deletes all file contents and places a file pointer at the beginning of the file. If the file doesn’t exist, it creates a new file and places file pointer at the beginning of the file.
How to append data to the file
Syn: open(FILEHANDLE,">>filename");
Ex: open(FH,">>sample.txt");
Note: In append mode if the given file exists, it opens a file and places a file pointer at the end of the file. If the file doesn’t exist, it creates a new file and places file pointer at beginning of the file.
close():
It is used for to close file, which is already opened
Syn: close(FILEHANDLE);
File Test commands:
-f:
It returns true if the given file is a regular file
-d:
It returns true if the given file is a directory file
-l:
It returns true if the given file is a link file
-e:
It returns true if the given file is exist
-z:
It returns true if the given file is empty
-r:
It returns true if the given file has read permission
-w:
It returns true if the given file has write permission
-x:
It returns true if the given file has execute permission
-T:
It returns true if the given file is a Text file
-B:
It returns true if the given file is a Binary file
Ex: file-existence.pl
#!/usr/bin/perl -w
#Program to check the given file exists or not
print "\n Enter a filename::";
chomp($fname=<STDIN>);
if(open(FH,"<$fname"))
{
print "$fname file exists\n";
close(FH);
}
else
{
print "\n $fname file doesn't exist\n";
}
Ex: file-existence1.pl
#!/usr/bin/perl -w
print "\n Enter a filename:";
chomp($fname=<STDIN>);
#die: Predefined function, used to terminate the program
#$!: It displays perl generated error message
die "cann't open a file. $!" unless(open(FH,"$fname"));
print "\n$fname file exists";
close(FH);
print "\n";
Ex: file-open.pl
#!/usr/bin/perl -w
#Program for opening a file
print "\n Enter a file name:";
chomp($fname=<STDIN>);
die "cann't open a file. $!" unless(open(FIN,"$fname"));
while($x=<FIN>)
{
print "$x";
}
close(FIN);
Ex: file-open1.pl
#!/usr/bin/perl -w
print "\n Enter a filename:";
chomp($fname=<STDIN>);
die "Can't open a file. $! unless(open(FH,"$fname"));
@x=<FIN>;
print "@x";
print "\n Total lines:",$#x+1;
close(FIN);
Ex: print-oddlines-from-file.pl
#!/usr/bin/perl -w
print "\nEnter a filename:";
chomp($fname=<STDIN>);
die "Cann't open a file.$!" unless(open(FIN,"$fname"));
$i=0;
while($x=<FIN>)
{
$i++;
next if($i%2==0);
print "$i.$x";
}
close(FIN);
Ex:
create-file.pl
#!/usr/bin/perl -w
print "\nEnter a filename to be created:";
chomp($fname=<STDIN>);
open(FOUT,">>$fname");
print "Enter data to the file and press ctl+d:";
while($x=<STDIN>)
{
print FOUT "$x";
}
print "**********$fname file created*********\n";
close(FOUT);
Ex: check-file-type.pl
#!/usr/bin/perl -w
print "\nEnter a file name:";
chomp($fname=<STDIN>);
if(-e $fname)
{
if(-f $fname)
{
print "\n $fname is a regular file\n";
}
elsif(-d $fname)
{
print "\n $fname is a directory\n";
}
}
else
{
print "\n$fname file doesn't exist\n";
}
Directory Handling
Directory is a collection of files
Directory Functions
opendir()
: It is used for to open directory
opendir(DIRHANDLE,"dirname");
ex: opendir(DH,"abc");
readdir():
It is used for to read files from given directory
readdir(DIRHANDLE);
ex: readdir(DH);
rewinddir():
It places pointer at the beginning of the given directory
rewinddir(DIRHANDLE);
ex: rewinddir(DH);
closedir():
It is used for to close the directory which is already opened
closedir(DIRHANDLE);
ex:closedir(DH);
mkdir():
To create a new directory
mkdir(dirname);
ex: mkdir("dirname");
chdir():
To change directory
chdir(dirname);
ex: chdir("abc");
rmdir():
To remove a directory
rmdir(dirname);
ex: rmdir("abc");
Ex:file-count.pl
#!/usr/bin/perl -w
#WAP to accept a directory and print all files and count no of file
print "\nEnter a directory name:";
chomp($dname=<STDIN>);
die "Can't open a directory. $!" unless(opendir(DH,"$dname"));
$cnt=0;
while($x=readdir(DH))
{
print "$x\n";
$cnt++;
}
print "\nTotal no of files in $dname directory: $cnt\n";
closedir(DH);
Ex:
dir-subdir-count.pl
#!/usr/bin/perl -w
#WAP to accept a directroy and count no of files and no of sub directories
print "\nEnter a directory name:";
chomp($dname=<STDIN>);
die "Can't open a directory. $!" unless(opendir(DH,"$dname"));
$fcnt=0;
$dcnt=0;
while($x=readdir(DH))
{
if(-f $x)
{
$fcnt++;
}
elsif(-d $x)
{
$dcnt++;
}
}
print "\nTotal no of files in $dname directory:$fcnt";
print "\nTotal no of subdirectories : $dcnt\n";
closedir(DH);
Ex: rem-directory.pl
#!/usr/bin/perl -w
#WAP to remove directory
print "\nEnter a dir name to remove:";
chomp($dname=<STDIN>);
rmdir($dname);
print "*******$dname directory has been deleted********\n";
Regular Expressions
Any string contains wild card character known as regular expression
Wild card characters: *, ., ?, [, ], -
t.*t à Regular expression
/t.*t/ à Pattern
The 2 binding operators are
=~ à It returns true if the given pattern found
!~ à It returns true if the given pattern not found
Wild card characters or Meta characters
1)* à It matches Zero or more occurrence of preceding character
2) + à It matches one or more occurrence of preceding character
3)? à It matches Zero or one occurrence of preceding character
4). à It matches any single character
5)[ ] à It matches any single character in the given list
6)[^] à It matches any single character other than in the given list
7)[-] à It matches any single character in the given range
8)(|) à It matches any one string in the list
9){m} à It matches exact occurrence of preceding character
10){m,n} à It matches min m occurrence and max n occurrence of its preceding character
11){m,} à It matches min m occurrence and max no limit of its preceding
12)^ à Start of the line
13)$ à End of the line
14)\d or [0-9] à Any single digit
[0-9] [0-9] [0-9] [0-9] or [0-9]{4} or \d\d\d\d or \d{4}
15)\D or [^0-9] à Any single non digit
16)\w or [a-zA-Z0-9_] à Any alphanumeric
17)\W or [^a-zA-Z0-9_] à Any non alphanumeric or special character
18)\s à ‘ ‘, ‘\t’, ‘\n’
19)\b à Word Boundary
Examples:
$str=~/perl/ à It searches the perl sting ( It will search character by character)
$str=~/\bperl/ à Word starting with perl
$str=~/perl\b/ à Word ending with perl
$str=~/^perl/ à Line starting with perl
$str=~/perl$/ à Line ending with perl
If($str=~/^perl$) à Line should contain only perl
If($str=~/^perl.*perl$/) à line starting with perl and line ending with perl
If($str=~/^$/) à blank lines
If($str=~/\b\d{4}\b/) à 4 digit number
If($str=~/\b\d{3,5}\b/) à searching 3 or 4 or 5 digit number
If($str=~/\b\w{3,5}\b/) à searching 3 or 4 or 5 digit character word
If($str=~/^\w+\s\w+\s\w+\s$/) à the line is having exactly 3 words
If($str=~/\b(2[6-9][34][0-9]5[0-5]\b/) à searching no b/w 26 to 55
If($str=~/\b\d{2}-\d{2}-\d{2}\b/) à 02-08-13
If($str=~/\b\d{2}-\d{2}-(\d{2}|\d{4}\b})\b/) à 02-08-13 or 02-08-2013
If($str=~m{\b\d{2}[-/]\d{2}[-/](\d[2]|\d{4})\b}) à 02-0-13 or 02-08-2-13 or 02/08/13 or 02/08/2013 or 02-05/13
If($str=~m{\b\d{2}([-/#])\d{2}/1(\d[2]|\d{4})\b}) à 02-0-13 or 02-08-2-13 or 02/08/13 or 02/08/2013 or 02/05/13
Substitution string by string
if($str=~s/Perl/linux/gi) à Every line all the occurrences
if($str=~s/^Perl/linux/gi) à Ever line first occurrence
if($str=~s/Perl//gi) à Replacing empty string
Translation character by character
If($str=~tr/a/t)
If($str=~tr/am/tp)
If($str=~tr/[a-z]/[A-Z]/)
PERL Predefined Functions
String Functions
1)ord():
It returns given character ASCII value
Print ord(‘a’); #97
Print ord(‘A’); #65
2)chr():
It returns given ASCII code character
Print chr(65); #A
Print chr(97); #a
3)uc():
It returns the given string in upper case
Print uc("pavan"); #PAVAN
4)lc():
It returns the given string in lower case
Print lc("PAVAN") #pavan
5)ucfirst():
It returns the given sting first character into upper case
Print ucfirst("pavan") #Pavan
6)lcfirst():
It returns the given string character into lower case
Print lcfirst("PAVAN") #pAVAN
7)length():
It returns the length of the given string
Print length("pavan") #5
8)substr("string,start,length) :
It extracts the specified portion from the string
Print substr("I like Perl",4,5); #ke pe
9) index(mainstring,substring):
It returns position of the substring in main string,
if substring not found in main string, it returns -1
print index("I like perl","perl"); #7
print index("I like perl","unix"); #-1
10) chop():
It deletes the given string last character
$str="I like perl";
chop($str);
print $str; #i like per
11) split():
It is used for to split the string into multiple values based on one or more delimiters.
$str="This is perl scripting class";
@x=split(" ",$str);
print "total elements:",$#x+1;
$str="This is,perl scripting:class";
@x=split(",| |:",$str);
Print "\n Total elements: ",$#x+1;
12) join():
It is used for to join multiple values into single string based on delimiter @num=(10,20,30,40,50,60);
$x=join(":",@num);
Print "$x"; #10:20:30:40:50:60
Array Functions:
- push() :
@x=(10,20,30,40);
Push(@x,50,60,70);
Print "@x"; # 10 20 30 40 50 60 70
@x=(10,20,30,40);
unshift(@x,50,60,70);
Print "@x"; 50 60 70 10 20 30 40
@x=(10,20,30,40);
$k=pop(@x);
Print "The deleted element is : $k"; #40
Print "@x"; # 10 20 30
@x=(10,20,30,40);
$k = shift(@x);
Print "The deleted element is : $k"; #10
Print "@x"; #20 30 40
@x=qw(one two three four five);
@y=sort(@x);
Print "@y"; #five four one three two
Print "@x"; #one two three four five
@x=qw(one two three four five);
@y=reverse(@x);
Print "@y"; #five four three two one
Print "@x"; #one two three four five
reverse(sort(@x));
splice(@oldarray,start,length,@newarray)
@x=qw( a b c d e f);
@num=(1,2,3,4);
splice(@x,2,3,@num);
print "@x"; #a b 1 2 3 4 f
splice(@x,2,0,@num);
print "@x"; #a b 1 2 3 4 c d e f
splice(@x,2,3)
print "@x"; #a b f
Mathematical Functions
- abs():
print abs(-45);#45
print sqrt(100); #10
print sqrt(abs(-100)); #10
Date and Time Functions
localtime():
Sub Routines or User defined functions
Function is a group of statements to perform certain task and it must return a value. The main concept of function is to reduce length code of the program, easy to maintain, supports reusability, reduces cost of maintenance.
Syntax:
&functionname(arg1,arg2,……); ---- > Calling Function
-----------
-----------
-----------
-----------
Sub funcationname ---- > called function or defining function
{
-----------
-----------
-----------
-----------
}
@_ is a special variable; it holds all function call arguments
Example 1:
sub hello
{
print "\n , hello, good evening";
}
hello;
print "\n bye, have a nice day";
Example 2:
&hello; #forward reference
hello;
print "\n bye, have a nice day";
sub hello
{
Print "\n hello, good evening";
}
Example 3:
display("hello","good","evening");
sub display
{
Print "Total no of args:", $#_+1;
Print "\n @_";
}
Example 4:
sum(10,20,30);
sub sum
{
($x,$y)=@_;
Print "\n sum=$n";
}
Example 5:
sum(10,20);
sub sum
{
$x=$_[0];
$y=$_[1];
$n=$x+$y;
Print "\n sum=$n";
}
Example 6:
sum(10,20);
sub sum
{
$x=shift(@_);
$y=shift(@_);
$n=$x+$y;
Print "\n sum =$n";
}
Example 7:
$n=&sum(10,20,30);
Print "\n sum1 = $n";
$n=$sum(10,20,30,40,50,60,70);
Print "\n sum2= &n";
sub sum
{
$total=0;
foreach $k (@_)
{
$total=$total+$k;
}
Return $total;
}
Example 8:
%days=("mon"=>1,"tue"=2,"wed"=>3,"thu"=>4,"fri"=>5);
&display(%days,"sat",6,"sun",7);
sub display
{
%h=@_;
while($x,$y)=each%h)
{
Print "\n $x week day no is : $y";
}
}
Example 9:
sub sum($\$); #prototype declaration
$a=10;
$b=20;
@x=(10,20,30,40,50);
sum($a,$b); #calling function
#sum($a); - wrong
#sum($a,$b,30,40); - wrong
#sum($a,@x); - wrong
sub sum($/$) # prototype declaration
{
$x=$_[0];
$y=$_[1];
$n=$x+$y;
print "\n sum=$n";
}
Scope of variables
1)our
2)my
3)local
The default scope is our scope.
The our scope variables can be accessed any where in the program
The my scope variables can be accessed within that block only.
The local scope variable can be accessed within that function and it child functions
Example 1:
$x=100;
&f1();
&f2();
Print "\n In main, x=$x, y=$y,z=$z"; # 110,empty,empty
sub f1
{
my $y=200;
local $z=300;
print "\n In f1, x=$x, y=$y,z=$z"; # 100,200,300
$x=$x+10;
&f3();
}
sub f3
{
print "\n In f3, x=$x, y=$y,z=$z"; # 110,empty,300
&f2();
}
sub f2
{
print "\n In f2, x=$x, y=$y,z=$z"; # 100,empty,empty
}
Example 2:
use strict; #It forces the user to declare variables explicitly
use warnings;
our $count=1;
our $x=10;
while($count<=3)
{
print "$x \n";
$x=$x+10;
$count=$count+1;
}
Command line arguments
At the time of execution of perl script, if user passes any arguments known as command line arguments. @ARGV is a special variable, it holds all command line argument values
Example 1:
#perl hello.pl pavan kumar Bangalore
print "\n Total no of Args:",$#ARGV+1;
Example 2:
#perl sum.pl 10 20
$n=@ARGV;
if($n= =2)
{
my($a,$b)=@ARGV;
my $c=$a+$b;
print "\n sum: $c";
}
else
{
print "\n Invalid Arguments";
}
Example 3:
#perl copy.pl sample.txt temp.txt
$n=@ARGV;
if($n= =2)
{
$src=$ARGV[0];
$tar=$ARGV[1];
die "can’t open a source file. $!" unless(open(FIN,"<$src"));
open(FOUT,">$tar");
while($str=<FIN>)
{
print FOUT "$str";
}
print "\n File copied successfully";
close(FIN);
close(FOUT);
}
else
{
Print "Invalid no of Arguments";
}
Modules:
Module is a collection of properties (variables, methods, functions)
- pakage is a keyword to create a module
- pakage name and module name must be same
- extension of the perl module is .pm
- the perl module must register in perl/site/lib directory
- module must return a true value
- main concept is reusability
- use and require are the keywords to import perl modules
- use keyword imports perl module properties and methods at compile time
- require keyword imports perl modules and methods at runtime
How to access perl properties and methods
<Module name>::<Method name>
Or
<Module name>;
$object_name=new
$object_nameà Method name
3 comments:
I really like your block..
this is very useful to me..
please post some real time isue .. like deployments and other..
plz replay me
and i want to contact you if plz post the contact
you can email me @pavankumarmca067@gmail.com
I'm AIX administrator weblogic app is new for me can u share some doc to start with same
Post a Comment