Vous êtes sur la page 1sur 14

PERL5LIB=D:\oracle\product\10.2.0\db_1\perl\5.8.

3\lib\MSWin32-x86;D:\oracle\prod
uct\10.2.0\db_1\perl\5.8.3\lib;D:\oracle\product\10.2.0\db_1\perl\5.8.3\lib\MSWi
n32-x86;D:\oracle\product\10.2.0\db_1\perl\site\5.8.3;D:\oracle\product\10.2.0\d
b_1\perl\site\5.8.3\lib;D:\oracle\product\10.2.0\db_1\sysman\admin\scripts;
blrtng
perldoc perlfunc --- lists all the built in functions
perldoc perl
$\="\n";
$,=" ";
-------------------------------------------------------------$\="\n"; #OUTPUT record separator. This can be used instead of \n in every print
statement
$/="a";
# Input record separator
$,=" ;" # Field separator. This can be used instead of saparating fields in eve
ry print statement
-- perl one liners
perl -e "print 'Hi'; "
--- Types of variables
1. Scalar
- which hold single value. should begin with $.
ex: $variable_name=value; $a=10; $str='abc';
2. Array
3. Associate array
4. File handle
5. type glob
-- Types of operators:
Arithmatic :+ - * / % ** ++ -- += -= /= %=
Numaric Relactional op : > >= < <= == != <=>
String relational op: gt ge lt le eg ne cmp
x repeative operator
print "hi" x 5;
$x=10;
print $x x 3;
.. range operators
print 1..10;
print a..h;
print Aa..zZ;
-- standard input file handle
STDIN # while reading from a file handle use <>
$x=<STDIN>;
print $x;
print "done";
chop $x; -- chop deletes last char of a string it could be anything
chomp $x
-- deletes input separator of a string
$/="a";
$x=<STDIN>;
chop $x;
print $x;
print "done";
-- false values : "", undef, 0, 0.0, "0"

if (cond)
{
stat
}
else
{
stat
}
----- loop control statements
next -- similar to continue
last -- similar to bread
goto latbalename
for ($i=1;$<=10;$i++)
{
next if $i%2==0;
print $i;
}
$1=1
{
last if $i>10;
print $i;
$i++;
redo;
}
foreach $v ($x, $y,$z)
{
$v++;
print $v;
}
foreach ($x, $y,$z)
{
$_++;
print $_;
}
-- To list all pre defined variable values:
perl -d
crlt +c
V
--- To execute OS commands
1.
$x=`dir';
print $x;
print `dir`;
`dir';
2.

system("notepad.exe);
3.
exec("notepad"); -- terminates prog after closing notepad
-- Arrays
Ordered collection of scalar items
size cannot be fixed
it supports only single dimention
index no. starts from 0
@ sympbol is used to define array.
@arrayname=(list of values);
@cities=("BLR',"HYD","MUM");
@a1=("abc",34,64.26,'def');
@a2=qw(abc 34 64.26 def);
print "@a2"
print @a1;
print $a1[1];
print @cities[0,4,2];
print @cities[1..3];
@cities[0,3]=@cities[3,0];
-- to find the size of an array
$size=@cities;
print scalar(@cities);
print $#cities; -- holds last index no. of that array
@ARGV -- holds command line argument
$0
-- contains the name of the script
$$
-- process id no. of the scipt.
$ARGV
$_
ctrl + z
ctrl + d
@a1=<STDIN>;
print @a1;
chomp(@a1=<STDIN>); #to remove new lines
-- Array functions
1. push
syntax: push arrayname,[list of values]
-- returns the new size of the array;
push @a1,1,2,3;
print push @a1,a,b,c;
print push @a1;

print @a1;
2. pop
deltes the last element of the array
sys; pop [arrayname];
returns the element deleted;
pop @a1;
print pop @a1;
print @a1;
print @ARGV;
pop;
print @ARGV:
-- Logical operators
&& || !
and or not
$host=shift||"abc.com";
print $host;
---- splice:
delete or insert anywhere in an array
syntax: spfile(array,offset,no. of lement to be delte,list of va
lues to be iserted)
@a1=(12,13,14,15,16);
splice @a1,2,1,'a','b','c';
print @a1;
splice @a1,1,0,'f','s';
print @a1;
splice @a1,2;
print @a1;
splice @a1;
print @a1;
print defined (@a1); # to check array exits or not.
-- delete
one or more element deleted
other than the last ele
@ch=(a..g);
delete @a1;
-- sort
syn: sort array;
-- by default asc order
-- returns new sorted array
@a=qw(abc xyx ijk pqr def);
@new= sort @a1;
print @a;
print @new;

Numerical order:
print sort {$a<=>$b} @a2;
print sort {$b<=>$a} @a2;
@a3=(12,34,"abc","xyx","we",1,,156, 33);
print @a3;
print sort @a3;
print sort {$a<=>$b || $a cmp $b} @a3;
-- revers
syn: revers array
returns an array in reversed array
print revers @a1;
-- split
syn: split pattern,string
returns array of values
$str="perl session 4 days";
@w= split "e", $str;
print @w;
-- join
syn:join pattertn, array
return a string
$s=join "e",@w;
print $s;
-- grep
syn: grep pattern/condition, array
this fun returns all the elements that satisfies te cond
@g=(1,5,34,7,12,8,22,82);
@dev2=grep($_%2==0,@g);
print @dev2;
@g2=grep(m/2$/,@g);
print @g2;
-- map
@m=map($_*2,@g);
print @m;
-- Associative array
it is also called as hash
it is an unordered collection of key value pairs
cannot fix the size
% is used for this
a key can have only one value
value can be undef but not the key name
syn: %hashname=(k1,v1,k2,v2,k3,v3,k4,v4,...);
syn: %hashname=(k1=>v1,k2,v2=>k3=>v3,k4=>v4,...);

%cities=("kar","BLR", "TN","ch","ap","hyd", "MH","MUM");


print %cities;
print $cities{"kar"};
print @cities{"kar","ap"};
-- there are 5 hash functions
1. kyes
@keynames=keys %cities;
2. Values
@listofvalues= values %cities;
3. exists
--returns tru if key name exists in a given hash
print exists $cities{"kar");
4. each
--returns one pair at a time or undef if called once mor
e than the total no. of pairs.
print each %cities;
print each %cities;
print each %cities;
print each %cities;
print each %cities;
while(@r= each %cities)
{
print @r;
}
5. delete
-- to deelte one or more pair
-- returns the value of the deleted key
print delete $cities{"kar"};
print delete @cities{"kar","MH"};
Built in hashes
%ENV
%SIG
%INC
-- Regular Expression
it is used for:
- to search for data based on patterns
- search for extract
- search and replace
- search and delete
m/pattern to search/options
s/pattern to search/pattern to replace/options
tr/pattern to search/pattern to replace/options
=~ is called binding operator
$_ is the default variable used by regular exp
$& stores the matched variable

$_="perl session 4 days";


print "found" if m/er/;
print "found -- $&" if m/es|er/;
print "found -- $&" if m/a./;
Quantifiers:
1. * - 0 or more times preceding character
print "found-- $&" if m/ez*s/;
2. + - 1 or more times preceding character
print "found-- $&" if m/ez+s/;
3. ? - 0 or 1 times preceding character
print "found-- $&" if m/ez?s/;
3. {n} - preceding character should be present at least n times
{n,} - min of n times
{n,m} - min of n times and max of m times
print "found-- $&" if m/ez{2}s/;
Character class [] -- single charector
[aeiou] [a-z] [0-9] [a-z0-9]
[1-256] -- 1|2|5|6
[0-9]
-- 1|2|3|... |9
[^aeiou] -- character other than a|e|i|o|u
$_="perl session 4 days";
print
print
print
print

$&
$&
$&
$&

if
if
if
if

m/[a-z]/;
m/[a-z]+/;
m/[^a-z]/;
m/[^a-z]+/;

Anchors -^ look at begining


$ look at end of the string
print "Found --$& " if m/^[a-z]/;
print "Found --$& " if m/[a-z]$/;
Metacharacters -\w
\W
\d
\D
\s
\S
\b
\B

---------

[a-zA-Z0-9]
[^a-zA-Z0-9]
[0-9]
[^0-9]
white space char
non whire space char
word boundry
non-word boundry

Numbered variables
$1 $2....

when pattern enclosed () matches some data

Backreferences
looking for the previous matched data in the same pattern
numbered variables
$1 -- 1
$2 --- 2
$_="to bee orr not to be";
m/([a-z])\1/; # ee
print $&
m/([a-z]).*\1/; # to bee orr not t
print $&
Options which can be used with m
i -- case insensitive
$x="Haste is waste";
print $& if $x=~/[a-z];
print $& if $x=~/[a-z]/i;
s -- make . match newline char also
g -- global -- multiple occurances
@ch=$x=~m/[A-Z]/g;
print @ch;
m -- mutliline search-- make ^ match at the begining of each lin
e
x -- ignoring space
(?#) -- to include comments with options
Substitution:
s always returns no. of replacements made
$_="hello world";
print s/o/z/g;
print uc("hello");
print ucfirst("hello");
print ucfirst("hello world");
s\b./uc($&)\eg;
if function is used then we have to use option 'e'
tr -- transliterate
char to chat
returns no. of rplacement made
$_="hello world";
tr/elo/xyz/;
print;
tr/elo/xy/;
print;

------------------perldoc perlre: for regular exp document


Subroutines/functions/methods
- can take any no. of args
- arg passed are always stored in a predefined variable @_
- always returns a value. and value rerurned depends on the last statement e
xecuted within the sub.
- & symbole is used for sub
- syn:
sub subroutine_name
{
statements
}
- to call sub
subroutine_name [Arguments];
&subroutine_name [Arguments];
sub display
{
print "HI";
}
display;
&display;
display();
&display();
Passing arguments to sub
sub arg
{
print "Args: @_";
}
arg;
arg 2;
$x=10;
$y=15;
arg $x,$y,90;
@array=(1..10);
arg @array;
Scope of variables
default scope is global
our -- default
local -- used for chaning global var temporarily
my
-- varibales which exists only in block
my $x=2;
$y=9;
our $z=12;
sub s1
{
my $x=8;
local $y=6;
$z++;
local $a=18;
print $X,$y,$x,$a;
}

sub s2
{
print $X,$y,$x,$a;
}
s1;
s2;
print print $X,$y,$x,$a;;
------------------------------------f1.pl
sub s1{\
{
print "S1";
}
sun s2
{
print "s2";
}
1;
------------------------------------f2.pl
#unshift @INC,"c:/";
require f1.pl;
s1();
s2();
------------------------------------References
Is term used for pointers
A ref var is defined as scalar that holds memory address of another var.
\ is used to extract memory address of any variable
$x=10;
print \$x;
$y=\$x;
To Deference a scalar address use $
print $$y; -- value contained in the address
$z=\$y;
print $z;
print $$$z; -- Value of x;
Array reference
@a1=(1..5);
print \@a1; -- address of the table
print \$a1[0]; -- address to the first element of the array
$r=print \@a1
print
print
print
print

@r; -- for all the elements


$$r[1]; - for single elements
@$r[1];
@$r[3,1];

@a1=(12,5,6,7);

@a2=(67,22,56,@a1,90);
@a3= 5,8,1,\@a2,66);
print ${$a3[3]}[1];
$p=$a3[3];
print $$p[1];
print $a3[3]->[1];
print @{$a3[3]}[4,6]; -- t0 print 5,7 of a1;
Anonymous array
$arr=[12,1,4,6,7];
#@a1=
#$arr=\a1;
Anonymous hash
$arr={1,a,2,b,3,c};
XML-----------------------------use XML::Simple;
use Data::Dumper;
$r=XMLin("simple.xml");
print Dumper($r);
$r->{"server"}->{"sahara"}->{"address"}->[0]="10.0.0.102";
print Dumper($r);
XMLout($r,"outputfile"=>"newsimple.xml");
File handling
------------------------it is similar to file pointer of C language
STDIN STDOUT STDERR ARGV are stanard files
syn: open filehandle,"mode filename";
open filehandle,mode,filename,permissions
modes: --- >
<
>>
+>
+<
+>>
+> write + read
+< read + write
open (FH,">data.txt");
print FH "line 1";
print FH "line 1";
print FH "line 1";
print FH "line 1";
close FH;
File append
open (FH,">>data.txt");
print FH "newline1";
print FH "newline2";
print FH "newline3";
close FH:

File write + read


open (FH,"+>data.txt");
print FH "perl";
print FH "shell";
print FH "TCL/TK";
# seek filehandle,offset,whence
- 0 for
bigining of file,1 from current position, 2 from end of the file
# tell returns current position
seek FH,0,0;
@lns=<FH>;
close FH:
print @lns;
# This will read file line by line and removes # and also takes
the backup of the file.
perl -i.bak -p -e "s/^#//" conf1.txt conf2.txt
# TO remove lines begining with #
perl -i.bak -p -e "s/^#.*//s" conf1.txt conf2.txt
# TO display lines begining with #
perl -n -e "print $_ if m/^#/" conf1.txt conf2.txt
File Test operators
-e
print glob("*.txt");
unlink test.txt # to delete a file
rename filename,newfilename;
Directory handle
opendir(DIR,"test");
while ($d=readdir(DIR))
{
print $d;
print $d;, ":", -s "./test/$d";
}
closedir DIR;

Pragma -- compiler directive


---------------------------------------use - to enable pragma
no - to disable pragma
1. strict
syn: use strict;
- it checcks ariable are declared with scope.
- symbolic refereces are not allowed
- bare words are not allowed.
2. English
syn: use English;

s_="abc1234abv";
m/\d/;
print $MATCH;
print $PREMATCH;
3. constant
use constant PI=3.14;
print PI;
4. use integet;
print 10/3;
5. use warnings;
6. use subs;

Exception handlings
-------------------------------------------- use 'eval' to catch exceptions and continue executing next commands
print "Enter 2 no.";
$x=<STDIN>;
$y=<STDIN>;
eval
{
$z= $x/$y;
print $z;
}
print $@ if ($@);
print "done";

Package
---------------------------------------------- its a collection of subroutines and/or variables
- to avoid subs naming conflicts
- default name in perl is name
- only global variables belong to the package
- every package has a symmbol tableof its own which contains globale var
iables and subroutines names
- 'use' - loads package at compile time
- 'require' - loads package at run time
package p1;
# following 3 steps are for exporting package. so no need to mention pa
ckage name in perl file.
use exporter;
our @ISA=wq(Exporter);
our @EXPORT=qw(&s1 @arr);
my $x=0;
our @arr=(12,1,3,4,5);
sub s1
{

print "pk 1";


}
sub s2
{
print "pk 2";
}
To include perl files to path:
unshift @INC,"c:/";
use lib "c:/";

Vous aimerez peut-être aussi