Perl 5.18 Learn

Perl 5.18

Setup on Windows: http://www.perl.org/get.html

  1. 1.       ActiveState Perl:  has binary distributions of Perl for Win32 (and Perl for Win64). http://www.activestate.com/activeperl/downloads
  2. 2.       Strawberry Perl: A 100% Open Source Perl for Windows that is exactly the same as Perl everywhere else; this includes using modules from CPAN, without the need for binary packages. Help is available from other Windows Perl developers on the #win32 irc channel on irc.perl.org
  3. 3.       DWIM Perl for Windows: A 100% Open Source Perl for Windows, based on Strawberry Perl. It aims to include as many useful CPAN modules as possible. It even comes with Padre, the Perl IDEexternal link.

Learning

  1. 1.       http://learn.perl.org/
  2. 2.       http://perlmaven.com/perl-tutorial

IDE For Development

  1. 1.       http://padre.perlide.org/  (dwim perl)
  2. 2.       Sublime Text
    1. a.       ModernPerl
    2. b.      PerlTidy

                                                              i.      To reformat Perl source code with PerlTidy, open your Perl file of choice and hit `Control+Shift+t`.

  1. 3.       http://www.perl-express.com/
  2. 4.       http://open-perl-ide.sourceforge.net/
  3. 5.       People who are already Eclipse users might want to know that there is a Perl plug-in for Eclipse called EPIC. There is also a project called Perlipse. : http://www.epic-ide.org/
  4. 6.       http://www.activestate.com/komodo-ide

 

 

Training TO DO

 

 

Advertisements

Perl Advanced

Topics :

 

  • How Perl supports OO Programming techniques;
  • How to write and use classes;
  • Advanced usage of regular expressions, including non-capturing groups, global (multi-line) matching, lookahead and lookbehind, and building readable regular expressions;
  • Working with persistent data using tie variables and DBI;
  • The eval function and its use in runtime exception handling;
  • Unix signal handling;
  • Testing strategies and supporting modules;
  • Producing and reading diagnostics from Perl programs;
  • Debugging techniques for Perl

 

Perl Basic Self Notes

Web: CGI Perl

BioPerl

Developed on UIXin

Derived from c + c++ + shell + sed (psed editor crosplatfoem)  + awk

 

Used for automation

Cross Platform Script language 100+ OS

Practical Extraction & Reprting Lang

Linux unix and mac, have active perl installed with the OS

Strawberry perl is created withby windows

Gcc: c compliler (cl in win) is needed by perl

Strawberry perl comes with gcc..windgw compiler, active does’t as unix has it in the OS

Make is dist as nmake and dmake

DWIM (do what I mean) perl comes with a f/w style with IDE and basic libs. It’s a flavor of strawcerry

Most use 5.8 as most modules are depedet on it

5.18 is not bkwd compatible with 5.18

Perl 6 will have co,pliters for 8 and 18

Perlmonkers is site for queries..hence people gont use perl license and perl official support

Comopiler perl.exe

Perldoc.exe  (java doc + man)

Corelibs – default libs (socket, net::telet)…

Utils: cpan + a2p psed h3xs pod2html…

Editors: Active Pro Studio (komodo is part of it), epic, dz-soft, perl open ide

 

Types

Scakar ($), list array hash

Loosely typed

Auto memory managemt

Implicit ttyper conversion, so no overflow exveption

Float can store infinity, no limit

In script ing lang as type is not known at compile time, the defarult value of all var of all types is undef.

Namig

User def: starts with alpha

Inbuild: starys wih special char or no.

$ARG (represets $_ for readibility) with Use English; flag

$a = 10; $b ; $c = $a + $b; c = 10 as when reading undef like int its 0 and when as string its null

$a = “hello”; $b ; $c = $a + $b; c = null

Perl is case sensative

O/p: print “ ”, printf

I/P: $a = <STDIN> or its alias <stdin>

UIX: #! /usr/bin/perl (#! Is shbang)

 

No amespace in c, so canot increment outer a if inner a is there

I C++ owards namespacig , LEADING to symbol tables

A namespace is a package

A 3rd party package is a lib.

 

In perl file abc.pl, package main is implicit

Print “a = $a\n” is same as “a = $main::a\n” (:: scope resolution)

Perl new.pl

Perl does not trim off \n that user presses at end of I\p, so do chop or chomp

chomp($name = <STDIN>;)

 

perldoc -f chomp

perldoc -q chomp

perldoc LibraryName eg. perldoc print

OR file:///C:/Perl64/html/index.html in active perl docs but http://perldoc.perl.org/ is better

 

 

perldoc perlvar : list of variables

 

$str = “happy”; is internally a array of char

U can refer positive and negative index that u can use to search

But it ever returns –ve indiex

Can cut from right

Overloaded fn are there

Pass by value and ref there

print “Enter name:\n”;

$|=1; // In komodo to debug, u have to emoty buffer forcefully :

chomp($name = <STDIN>);

print “Hello $name World”;

 

so if have to do stuff like : print uc(substr($str, 0, 3)).reverse(substr($str, -3));

 

It doesn’t throw exceptions like index out of bound…it returns undef and moves on.

To catch such stuff execute as perl –w, or use scrict; and use warning in code to get all warnigs …

Always run with these 2 statements

 

Private Public is my and our respectively from 5.8

In 5.0 our variable is declared as use vars qw($str); //quoted word

 

q($str)

qq($str)

(‘$str’, ‘$b’), can be replaved by qw($a $b) shortcut way

 

In script

$a = 10;

$a = ‘10’;

$a = “10”; are all same statically and is interpreted at runtime

Perl is compiled and run on PVM (Perl VM) like JVM

S1 or s2 // execute  2 only if 1 fail

S1 and s2 //execute 2 only if 1 successful

Diff from c1 && c2

Perl –c a.pl

Perldoc –b

Perl compiler is object oriented…

Only 3 data types : int float and string

Strings are mutable

The type is interpreted based on the operator

Use int operators only on int (though any string operator ca e used on int) as strig operators do bitwise comparison so each char will be compared

Also ote that int operators canot be ised on strig

So $a = “test” and $b = “wer”

The $c = $a + $b; does $c = atoi($a)+ atoi($b); this atoi (alphaber to it) is c function and returns 0 if encounters non number

Hence

So $a = “1test” and $b = “12wer” gives $c = 13

 

Same is true for logical operators…

Loops : Until and unless, if elseif, else

In 5.8 there is pm (perl module) Switch.pm: switch case else. This is not a language feature. It’s a function of the library

In 5.10 owards there is native keyword for this: given –when – default

 

5.8

Use Switch; # it’s a core library

Use can

  1. 1.       Include lib
  2. 2.       Enable compiler options (use warings)

 

Say is println in perl

Given and when is version specific ie available only with 5.10

So in code say use v5.18; # tells the user what is the min version

 

6.0 will run the 5.8 code but vice versa is not true

So that it gives the correct error of version and not rubbish errors

 

To find if I/p is alpha or no do

Geven (input char)

{

When (/[a,e,I,o,u]/) {say ‘vovel’}

When (/[0-9])>>(]/) {say ‘number’} # [0..9] is perl

}

 

Types in Perl include strig, char, int float, ref, glob (kinda ref)

 

List and array are heterogenous containers, array is named list…

Hash is also type of list

Foreach $i (10, “hello”) {}

(10, “hello”) is a python touple ie costant and immutable

Foreach (1..10)

Say $_

 

$i is ref to the container elements$_ is the this pointer that’s passed to every fn. this is only in foreach.

All scalar functions take $_ and work on that only when no parameter is passed. This is implemented using default argouennts

Undef is generic type

Null is specific type (string type)  $a = ‘’; here a is null;

$a = undef; # a is undef now

 

($a, $b) = (4,5);

Swap ($a, $b) = ($b, $a)

($a, $b) = (4,5,6)[-1,-2]; means that a is -1 index ie 6 and b is 5..

(‘mon’, ‘feb’) OR qw (min tue)

$_ = ‘hai’; //Scalar fuctions

Print uc;

 

@arr is array

 

U can ask perl to escape stuff using //

Use localtime in time based apps

($a, $b) = (localtime(time))[3,4];

($d, $m,$y)= split(/[\-\/]/, $date); # \ insdide the [] is to escape

http://search.cpan.org/search?q=date+manip;s=0 use such CPAN libs for easing ur Job. In morgan its instmodsh command in cmd

http://perlmonks.org/ for FAQs

 

 

 

ARRAY is c’s Indexed Linked List and so can insert elvements without relocating the subsequenst

It’s a named ordered list

$#arrayname returs index of last elemet

Use $arr[0] to access, not @arr[0], as with latter, when u do <STDIN>, cos with latter it goes on infinitely and so will keep accepting till end of line (or ^z in cmd prompt)

When selecting multiple @arr[1,2,1];

Complete array @arr

Length $#arr + 1; OR @arr OR scalar @arr // rarely used as implicit casting

Contexts in cheatsheet is typecasting

 

 

IMBED PERL IN JAVA etc. : http://swig.org/ or native utilities…

 

BEFORWE USING CPAN, use CORE MODULES: http://perldoc.perl.org/index-modules-L.html  OR perldoc List::Util

-f is for fuction

 

use List::Util qw(max min); for including the utility functions

 

map ($_++, @arr);

@arr= map(uc, @arr);

OR

Map ($_=uc, @arr)

 

@chars = map(substr($_, -1,@arr));

@cumulativeSum = Map($sum+=$_,@arr)

Find pattern (grep)

@res = grep(/50/, @arr)// returns 50 250 500 etc.

 

($first,$last)= (split(/ /,$str))[0,-1];

/ +/ #space + means one or more spaces

 

If delimeter is -, escape it

>1 delim in []

// means char by char split

/ */ means char by char split excluding space (* means 0 or more)

 

Qs

How is pass by ref implemented

Take the notepad notes

Adv notes cd from anyone

How to create objectsDee

Perl Basic Notes

>>Basic perl constructs
>>Data structures
scalar
list
array
hash
>>building u r own regex
>>subroutines
>>files

 

>>Complex Data
>>packages & Modules

>>Object Oriented Module development
>>Adv Regular Expressions
>>perl CORE modules
DBI
CGI
& more
========================================================
Eval precedence:-
=================
when we are de-refering
if the references are stored in a ARRAY/HASH
then it is compulsory to use a FLOWER BRACKET
to de-refer it

Arrow Rule:-
============
Arrow is OPTIONAL b/w two subscripts/index
$num=10;
@arr=(2,4,6,8,10);
%hash=(‘a’=>1,’b’=>2);
sub fun{ print “Hello from fun\n”; }

$r1=\$num;
$r2=\@arr;
$r3=\%hash;
$r4=\&fun;

@refs=($r1,$r2,$r3,$r4);

print “SCALAR = ${$refs[0]}”;
print “ARR = @{$refs[1]}”;
print “HASH = “,%{$refs[2]};
{$refs[3]}->();
>>AoA
>>AoH
>>HoA
>>HoH (most used)

==========================================================

Anon:-
=======

$ref=[];
$ref={};

OR

Autovivification if the index exists OVERWRITE
if the index doest exists CREATE NEW
$ref;
$ref->[0]=20;

$ref;
$ref->{a}{b}=1;

 

 

$ref=[1,2,3,4,5,[7,8,9]];

print “$ref\n”;

 

ex1:
$ref=[{a,b,c,d},{1,2,3,4}];

Identify the type of CDS ?
AoH

How do i print “b” ?
$ref->[0]{a}

How to all the keys of secnd hash ?
keys(%{$ref->[1]})
ex2:
$ref={a=>{n1=>[1,2],n2=>[3,4]},b=>{n3=>[5,6],n4=>[7,8]}};

Identify the type of CDS ?
HoHoA

How to print 1 ?
$ref->{a}{n1}[0]

How to print complete array ie 5,6
@{$ref->{b}{n3}}

How to print all the keys of FIRST hash ?
keys(%{$ref->{a}});
ex3:
$ref={north=>[1,2,3],south=>[4,5,6]};

Identify the type of DS ?
HoA
How to print “1” ?
$ref->{north}[0]
How to complete array of south?
@{$ref->{south}}
ex4:
$ref=[{a=>1,b=>2},[c,d,e,f],{p=>3,q=>4}];

Identify the type of DS?
AoH
AoA
How to print “1” ?
$ref->[0]{a}

How to print c,d,e,f
@{$ref->[1]}

How to print th keys of last hash
keys(%{$ref->[-1]});

 

ex5:
$teams={
mum=>{e1=>ename1,e2=>ename2},
chn=>{e1=>ename3,e2=>ename4},
hyd=>{e1=>ename5,e2=>ename6},
blr=>{e1=>ename7,e2=>ename8}
};
identify the type of DS?
HoH

How to print ename1 ?
$teams->{mum}{e1}

How to print keys of blr ?
keys(%{$teams->{blr}});
==========================================================
@loc1=qw(mum chn hyd);
%team11=(e1=>ename,e2=>ename,e3=>ename);
%team12=(e1=>ename,e2=>ename,e3=>ename);
%team13=(e1=>ename,e2=>ename,e3=>ename);
%team1=(mum=>%team11,chn=>\%team12,hyd=>\%team13);
@date=(d1,d2);
%r1=(name=>’IMS’,
location=>\@loc1,
team=>\%team1,
dates=>\@date);
);
%hash=(105=>\%r1);

How many variable names are used ? 7+
for every row 7

$ref={105=>{name=>’IMS’,
location=>[mum,chn,hyd],
team=>{mum=>{e1=>ename,e2=>ename},
chn=>{e1=>ename,e2=>ename},
hyd=>{e1=>ename,e2=>ename}
},
date=>[d1,d2]
}
};

 
How to debug/view the CDS?
==========================
use Data::Dumper;

$ref={};

print Dumper($ref);
=========================================================
$ref;
@arr=qw(1001-arun-sales-3232
1002-hari-purch-4343
1003-manu-accts-7373
1004-sami-sales-6363);

foreach (@arr)
{
($a,$b,$c,$d)=split(/-/);

$ref->{$a}{name}=$b;
$ref->{$a}{dept}=$c;
$ref->{$a}{salary}=$d;
}

Total salary of all the emps?

=========================================================
Packages & Modules:-
====================
>>package is a collection of variables & subroutines
>>every package will have its SYMBOL TABLE ie %PACKNAME
>>package name & modulename should be same
>>module filenames extension should be .pm
>>no she-bang for modules
>>package should be first line of u r module
>>every module should return TRUE at the END
>>one module will have one/more packages
>>Module name should be UNIQUE should not conflict
with CORE/Installed CPANs/PROP Modules
>>we access the variables & funs of package in this way
$PACKAGENAME::variablename;
PACKAGENAME::subroutinename();
>>Modules can be included in two ways
use Modulename; # compile time loading
require Modulename; # run time loading
>>special function named sub BEGIN{ }
is called automatically when module is LOADED
>> special function named sub END{ }
is called automatically when module is UNLOADED

We have a file named ” emp.txt”
u need to design a module
>>addEmp(1006,’john’,’sales’5454);
>>searchonDept(“sales”);
>>delEmp(1001);
>>displayAll();
once u r program exits “emp.txt” should be upto date

———————————————————-

@EXPORT

@EXPORT_OK

%EXPORT_TAGS=(g1=>[f1,f2,f3],
g2=>[f4,f5,f6]
all=>[f1,f2,f3,f4,f5,f6]);

———————————————————-
1) mkdir mylibs
2) mv Emp.pm mylibs
3) perl new.pl

What happened after the execution ?

>> use lib(“/home/arun/mylibs/”);
use Emp;

>> BEGIN{ push(@INC,’/home/arun/mylibs/’); }
use Emp;

>> use mylibs::Emp;
see later: perldoc -q @INC

———————————————————-
Diff Loader Schemes:-
=====================
SelfLoader – load on demand
AutoLoader – load on demand
See Later:
perldoc SelfLoader
perldoc AutoLoader

———————————————————-
How to know whether the module is installed ?
==============================================
perldoc Modulename

ex:
perldoc Socket
perldoc Net::Telnet

Only for windows:-
——————
perldoc -l Modulename
How to install a CPAN module:-
==============================
>> search for the path in cpan.org/other sites
>> there will be a cpan client locally available in ur
system
>> $ cpan
cpan> install Net::SSH
cpan> quit
>> $ perldoc Net::SSH
U have to download the TAR-BALL:-
=================================
>>should be root/sudouser

1) tar -gxvf module.tgz;
2) cd modulepath
(read the README file)
3) perl MakeFile.pl
4) make
5) make install
How to list all the Modules:-
=============================
$ instmodsh
see later:
perldoc -q installed
==========================================================

Object Oriented Perl Modules:-
==============================
>>Run Time Classes
>>Compile Time Classes
>>Moose Model

 

1) class – package

2) dynamic allocation in Java- new
new is keyword/operator

but in PERL we don’t have a keyword new
or operator an operator.

In perl new is a USERDEFINED METHOD

3) Every sub new will have IMPLICIT ARGUMENT
as classname itself
$class=shift;

$e1 = new Emp;
$e2 = Emp->new;

4) Every sub new will have bless as the last
statement of u r method

5) Every Member Function will have object itself
as a IMPLICIT ARGUMENT
$this=shift;

6) when we call a Member function using BLESSED REF

$e1->Memfun();

Emp::Memfun($e1);
Before BLESS
HASH(0x3232354)
After BLESS
emp=HASH(0x3232354)

After we bless the reference with class name
it is able to CALL the METHODS of package/class

 

package Emp;

sub new{
my $class=shift;
my $ref;
if(ref($_[0]) eq $class){
$ref->{code} = $_[0]->{code};
$ref->{name} = $_[0]->{name};
}
else{
$ref->{code}=shift||1;
$ref->{name}=shift||’noname’;
}
bless($ref,$class);
}

sub Input{
my $self=shift;
print “Enter the code : “;
chomp($self->{code}=<STDIN>);
print “Enter the name : “;
chomp($self->{name}=<STDIN>);
}

sub Print{
my $self=shift;
print “$self->{code} $self->{name}\n”;
}
1;

use Emp;

$e1 = Emp->new;
$e1->Print();

 

 

Complete the class
for the following main program

use Emp;

my @arr;
push(@arr,Emp->new(1,’hari’,9343));
push(@arr,Emp->new(2,’manu’,5454));
push(@arr,Emp->new(3,’arun’,6343));
push(@arr,Emp->new(4,’chet’,3454));
push(@arr,Emp->new(5,’dine’,4343));

Order the objects based on their salary
@arr= sort …. @arr;

foreach $i (@arr)
{
$i->Print();
}

 

Object as argument to the MEMBER FN:-
=====================================
$e1->Compare($e2);
Emp::Compare($e1,$e2);
sub Compare
{
($lhs,$rhs)=@_;
if($lhs->{salary} > $rhs->{salary})
{
return 1;
}
else
{
return 0;
}
}

==========================================================

Inheritance in PERL:-
=====================

by a special varible named as
@ISA

@ISA=qw(one two three);

Note:
every class is derived class of UNIVERSAL
can()
isa()

see later
perldoc UNIVERSAL

==========================================================
Polymorphism:-
==============
overloading
>>ctor
>>function
sub fun
{
if(@_==1) { for single arg function }
if(@_==2) { for single arg function }
if(@_==3) { for single arg function }
if(@_==4) { for single arg function }
unless(@_){ if no args are passed }
}

>>operator
within a package
use overload(‘operator’=>\&METHODNAME);
over riding
>>

emp.pm
======
package emp;

sub new {…..}
sub input{…..}
sub print{
$self=shift;
print “$self->{empa1} $self->{empa2}”;
}

manager.pm
==========
package manager;
use emp;
@ISA=qw(emp);

sub new {……}
sub getdata{……}
sub print{
$self=shift;
$self->SUPER::print(); # we can call in the derv mem-fn
print “$self->{mgra1} $self->{mgra2}”;
}
main.pl
=======
use manager;

$m1 = manager->new;
$m1->input();
$m1->getdata();
$m1->print(); # will call which method
# ie emp or manager
# ans : manager

how to invoke the “print” method the base class
$m1->emp::print(); # can be called in the mainprogram

 

run time type indentification (RTTI)
>>

$ob = fun();

$ob->f1();
$ob->f2() if(ref($ob) eq ‘SLL’)
$ob->f3() if(ref($ob) eq ‘DLL’)
$ob->f4() if(ref($ob) eq ‘CLL’)
OR
if($ob->isa(‘SLL’)) $ob->f2();
if($ob->isa(‘DLL’)) $ob->f3();
if($ob->isa(‘CLL’)) $ob->f4();

==========================================================
1) Run Time Classes in PERL
2) Compile Time classes in PERL

see later:
perldoc fields
perldoc base

3) CPAN Modules Class::MethodMaker
4) Moose Model

see later:
perldoc Moose

==========================================================
Exception Handling:-
====================
>>on-FLY execution
>>eval { Block };
>>eval is executed in different Thread
with same Lexical Context
>>if the eval is EMPTY is read from “$_”
>>if the eval FAILS is stores the error under
$@
>>eval block is not COMPILED
>>equivalent of throw in perl is => die

 

Write a perl program
to accept two nos & raise the Divide by ZERO Exception
then if there is an exception DISPLAY APPOR INFO
if there is no exception DISPLAY THE RESULT

ex:

print “Enter the no : “;
chomp($a=<>);
print “Enter the no : “;
chomp($b=<>);

eval
{
if($a==$b) { die(“TYPE1”); }
if($a<$b) { die(“TYPE2”); }
$c=$a/$b;
};

if($@=~/TYPE1/i) { print “Error1\n”; }
elsif($@=~/TYPE2/i){ print “Error2\n”; }
elsif($@=~/divi/i) { print “Error3\n”; }
else { print “Result = “,$c,”\n”; }
See Later
a cpan module named “Exception.pm”
which will provide us try/catch keywords

==========================================================
It is prefered to use
======================
croak instead of -> die
carp instead of -> warn

ex:
use Carp;

sub f4{
print “F4\n”;
croak;
}
sub f3{
print “F3\n”;
f4();
}
sub f2{
print “F2\n”;
f3();
}
sub f1{
print “f1\n”;
f2();
}

print “Main starts\n”;
f1();
print “Main Ends\n”;

==========================================================
caller method:-
===============
__PACKAGE__
__FILE__
__LINE__

package MyTest;

sub fun
{
($pack,$file,$line)=caller;
print “Package name = $pack\n”;
print “Filename = $file\n”;
print “Line num = $line\n”;

print “Package name = “,__PACKAGE__,”\n”;
print “Filename = “,__FILE__,”\n”;
print “Line num = “,__LINE__,”\n”;
}

sub BEGIN
{
fun();
}
package main;
print “MY MAIN STARTS\n”;
print “MY MAIN ENDS\n”;

==========================================================

%INC – will store all the modulenames u perlprogram
is dependent-on

ex:
use DBI;

print join(“\n”,keys(%INC));

==========================================================

To Debug the perl program:-
===========================

step1: $ perl -d programname.pl

step2: List the program with line number
<db> l

step3: u have to set the break points
already there is a break point set to FIRSTLINE
already in RUN MODE
<db> b 10
<db> b sum()

step4: List all the break points
<db> L

step5: Continue the program & stops at next break point
<db> c

step6: Single step mode is ENABLED
<db> s # Will debug the subroutines also
<db> n # Skip debugging the subs

step7: Data Inspection
<db> p $var
<db> p @arr

step8: U want to Modify the Variable value thru Debugger
<db> p $var=10

step9: U can add a HARDWARE watch to a variable
<db> w $a

step10 : AT any point of time u can exit the DEBUGGER
<db> q

Note:
perldoc perldebug

———————————————————-

Database Interaction in PERL:-
==============================

step1 : check whether u r perl has DBI.pm
perldoc DBI

step2: check whether u r DBD drivers are installed
perldoc DBD::oracle

OR

use DBI;
print join(“\n”,DBI->available_drivers());

 

ex1:

use DBI;

$dbh = DBI->connect(‘dbi:ODBC:sample’);

$dbh->do(“delete from emps where name=’777′”);

$sth = $dbh->prepare(“select * from emps”);

$sth->execute();

while(@arr=$sth->fetchrow_array())
{
print “$arr[0] $arr[1] $arr[2]\n”;
}

$dbh->disconnect();

 

 

 

use DBI;

$dbh = DBI->connect(‘dbi:ODBC:sample’,”,”,{AutoCommit=>0});

$dbh->do(“insert into emps values(8,’888′,88)”)
or $dbh->errstr;

$sth = $dbh->prepare(“select * from emps”);
$sth->execute();

$dbh->begin_work();
operation1 or $dbh->roll_back();
operation2 or $dbh->roll_back();
operation3 or $dbh->roll_back();
$dbh->commit();

while(@arr=$sth->fetchrow_array())
{
print “$arr[0] $arr[1] $arr[2]\n”;
}
#$dbh->disconnect();

 

Note:
perldoc DBD::CSV

==========================================================
Ties in Perl:-
==============

use Tie::File;

tie @arr, ‘Tie::File’, “data.txt” or die(“$!”);

$arr[0]=’Now i modified’;

untie @arr;
More Infor:
see Later
perldoc perltie
==========================================================

Singal Handling:-
================

Interrupts in UNIX is SIGNALs
On Unix :- $ kill -l

Signals like SIGKILL & SIGSTOP cannot be TRAPPED/HANDLED

when we execute the perl program
perl automatically captures
signal handler of the process to a special HASH
named %SIG

when is SIGINT is raised ?
cntrl + C
$SIG{‘INT’}=’IGNORE’;
foreach (1..20)
{
print “$_\n”;
sleep(2);
}

$SIG{‘INT’}=’DEFAULT’;
foreach (1..20)
{
print “$_\n”;
sleep(2);
}

Run this program & while it is executing press Cntrl+C

1) $SIG{‘INT’}=’IGNORE’;
2) $SIG{‘INT’}=’DEFAULT’;
3) $SIG{‘INT’}=sub { sub-body };
4) $SIG{‘INT’}=\&handler;

==========================================================
Process mgmt:-
==============

1) if u want to execute a perl program within a perl program

>> do ‘anotherperlprogram.pl’;
>> require anotherperlprogram.pl;

2) If u want to execute a Shell/OS/App Command
which is interactive

if($^O=~/win/i)
{
system(” Command “);
}

3) If u wan to execute a shell/OS/App process
which is Noninteractive & u want PERL TO CAPTURE
the output

@arr=`Command`;
OR
@arr=qx(Command);
==========================================================
fork – spwans the process

$pid=fork();
if($pid==0)
{
print “Hello\n”;
}
else
{
print “Bye\n”;
}
waitpid($pid,0);

 

Once we execute “exec”

exec – replaces the current process PCB
with its own PCB

==========================================================
IPCs:-
======
>> unix systemV IPCs – messageQ,sharedmemory,FIFO
>> Sockets, IO::Socket
>> Others

see later:
perldoc perlipc
1)
open(FH,”ls | “);

print <FH>;

close FH;
2)
open(PRN ” | lpr”);

print PRN “Hello\n”;

close PRN;
———————————————————-

 

 

 

 

 

 

 

 

 

 

 

 

 
Shell Scripts:-
===============
#!/bin/bash

shell scripts

exec perl -x $0
#!perl
print “Hello”;
print “hai”;

 
Shell Scripts:-
===============
#!/bin/bash

shell scripts
echo “I am shell starting”

perl << END_OF_PERL
print “Hello”;
print “hai”;
END_OF_PERL
echo “Back to shell”

 

 

 
———————————————————-
Threads:-
=========

use Thread;
use Threads::shared;

our $a=10;
shared($a);

sub task1{ lock($a);…. }
sub task2{ ….loc($a); }

$t1 = new Thread(\&task1); $t1->join();
$t2 = new Thread(\&task2); $t2->join();
==========================================================
Unit Testing : perldoc Test::Unit
perldoc Test

==========================================================
Regular Expressions:-
=====================

Metachars:
. [] ^ $ ? + * {} | () (?:)

Regex char classes:
\d \w \s \D \W \S \b \B

Regex operators :
$str=~m/REGEX/i;
OR
$str=~/REGEX/i;
$str=~s/REGEX/STATICSTRING/modifiers;
$str=~tr/RANGE/RANGE/;

Regex Memorization:
$str=~s/^(\w+)(\s.*\s)(\w+)$/$3 $2 $1/;

Regex Special vars: (EARLY MATCH)
print $` PREMATCH
print $& MATCH
print $’ POSTMATCH

 
In Perl we do have compile-time Regex:-
=========================================
$str=~qr/$pattern/; # pre-compiled Time

$str=~/$pattern/; # Run Time

 

I have to read the file:-
i have to search for pattern

1) pre-SALES
pre-sales
pre-SAles

2) purch

3) accts

#adding the modifiers within the REGEX:-
========================================

@pattern=qw(pre-(?i)sales purch accts);
open(FH,”data.txt”);

foreach $pat (@pattern)
{
print “$pat list\n”;
print grep(qr/$pat/,<FH>);
seek(FH,0,0);
print “\n”;
}
Regex matched across the MULTI LINE STRING:-
============================================
$str=~/REGEX/sm;

$str=~/REGEX/m;
ex:
$str=”tnew data text\nadded input\nend of the string”;

$str=~s/^t.*t$//m;

print “$str\n”;

Non-Memorizing patterns:-
————————-
example for (?:)
example for (?# comments)

ex:
$str=’sampled data added was given’;
$str=~/^(?:\w+)(\s.*\s)(\w+)$/;
print “$1\n”;
print “$2\n”;
print “$3\n”;

ex:

@str=(‘hello world of perl’,
‘bye from perl’,
‘new to perl’,
‘hai to perl’);

foreach (@str)
{
if(/^(?:hello|bye|hai)(?#words starting).*/)
{
print “$_ = $1\n”;
}
}

Don’t Replace the ORGINAL STRING:-
———————————-
$str=’hello world’;
$res = $str=~s/[aeiou]//rgi;
print “$str\n”;
print “$res\n”;
Tricks:-
——–
trick1:-
$x=”Bill the cat”;
$x=~s/(.)/$chars{$1}++;$1/eg;

trick2:-
$x = “cat dog house”; # 3 words
while ($x =~ /(\w+)/g)
{
print “Word is $1, ends at position “, pos $x, “\n”;
}

trick3:-
/(?i)yes/; # match ‘yes’ case insensitively
/yes/i; # same thing

 
Look Behind Positive Assertion:-
——————————–
(?=REGEX)

ex:
$str=’i traveled mumbai chennai’;

# costly
if($str=~/delhi/&&$str=~/mumbai/&&$str=~/chennai/)

#cheaper
if($str=~/(?=.*delhi)(?=.*mumbai)(?=.*chennai)/)
{
print “Yes”;
}
else
{
print “No”;
}
Look Ahead Positive Assertion:-
——————————–
(?<=FixedPattern)
Negative Look Behind Assertion:-
——————————–
(?!REGEX)
Negative Look Ahead Assertion:-
——————————–
(?<!REGEX)

$x = “I catch the housecat ‘Tom-cat’ with catnip”;

$x =~ /cat(?=\s)/;

@catwords = ($x =~ /(?<=\s)cat\w+/g);
# matches,
# $catwords[0] = ‘catch’
# $catwords[1] = ‘catnip’
\$x =~ /\bcat\b/; # matches ‘cat’ in ‘Tom-cat’
$x =~ /(?<=\s)cat(?=\s)/; # doesn’t match; no isolated ‘cat’ in
# middle of $x
ex:
$x = “foobar”;
$x =~ /foo(?!bar)/; # doesn’t match, ‘bar’ follows ‘foo’
$x =~ /foo(?!baz)/; # matches, ‘baz’ doesn’t follow ‘foo’
$x =~ /(?<!\s)foo/; # matches, there is no \s before ‘foo’

 

=========================================================

Perl Advanced Notes

Basic & Inter Perl
===================
ie Scalar/List/Array/Hashes/
References/Regex/Subs/Modules/Files

Advanced Perl:-
===============
>>Complex Datastructures
>>Packages & Modules
>>Object Oriented Modules
>>Advanced Regex
>>Tie & DBI
>>Exception Handling in perl
>>Debugging
>>Process management
>>Signal Handling
SCALAR variables:-
==================
scalar variable – $
scalar context
default value – undef
check for undef – if(defined($var))
string fns – uc/lc/index/length/reverse/substr
Inbuilt vars – var name is madeup specia/no

OUTPUT statement:-
==================
print “statement”;
printf(“statement”);
$res=sprintf(“statement”);

INPUT statement:-
=================
$var=<STDIN>; # prefered
read STDIN,$var,10; # reading from the file

PL-File:-
=========
-Implicit package is ie “main”
-What is She-Bang ie #! intr-path

method1: perl first.pl
method2: ./first.pl

Help system:-
==============
perldoc -f function-name
perldoc -q “string”
perldoc Modulename

-perldoc perlfunc
-perldoc perlop
-perldoc perlvar
-perldoc perlcheat

Branching:-
===========
– if-else
– unless-else
– given-when (new feature added 5.10 & above)

Loops:-
=======
for/foreach
while/until
dowhile/dountil

Note: w.r.t foreach is $_

Keywords:-
==========
last
next
redo

———————————————————-
List:-
======
(10,20,30,40);
(1..10);
qw(hello world of perl);
# space is delim
# it cannot interpolate
($a,$b)=(10,20);

———————————————————-
Arrays:-
========
@arr=(10,20,30,40);
$arr[0] / $arr[-1]
@arr[1,2,3]
@arr
$#arr
scalar @arr
traverse : for-loop and foreach
fns : push/unshift/pop/shift/reverse/sort
grep/map/split/join/splice

grep(/regex/,@ARRAY);

ex:
@values=qw(hari 123a a123 a123a 12a12 54 manu 65 123 56);
@res = grep(/^\d+$/,@values);

ex:
# perl sam.pl emp.txt sales
open(FH,”< $ARGV[0]”);
@res=grep(/$ARGV[1]/,<FH>);
print @res;

map(expression/Function,@ARRAY);

ex:
@arr=qw(Sun Mon tues wed);
@res=map(uc,@arr);
print “@arr\n”;
print “@res\n”;

ex:
@arr=qw(Sun Mon tues wed);
map($_=uc,@arr);
print “@arr\n”;
Note: If $_ is modified the INPUT array is also Modified

ex:
use List::Util qw(sum);
open(EMP,”$ARGV[0]”) or die(“$!”);
print sum(map((split)[-1],grep(/$ARGV[1]/,<EMP>)));
Hashes:-
========
-Unordered Data Structure

%hash=(“alpha”=>10,”beta”=>20,”gamma”=>30);
%hash=qw(alpha 10 beta 20 gamma 30 delta 40);

$hash{alpha};

@hash{alpha,beta,delta};

%hash;

fns – exists/delete/keys/values/each
traverse – while-each / foreach
sort – based on key
based on value

Note:
print “%hash”; # hashes cannot be INTERPOLATED
print %hash; # not a readable output

==========================================================
Aliasing:-
==========
Arrow Rule:-
————
arrow is optional b/w two indexes

Eval precedence:-
—————–
can be over-ridden using {}

AoA:-
======
@a=(10,20,30);
@b=(40,50,60);
@res=(\@a,\@b);

how do i print 20 ? $res[0][1]
how do i print 2nd row ? @{$res[1]}
AoH:-
=====
%ground=(ip1=>host1,ip2=>host2);
%floor1=(ip1=>host1,ip2=>host2);
%floor2=(ip3=>host3,ip4=>host4);

@res=(\%ground,\%floor1,\%floor2);

What is the system details in secnd floor with “ip4”
$res[2]{ip4}

How many system are there in ground floor ?
$len = keys(%{$res[0]});

List all the IP’s in first floor ?
keys(%{$res[1]});

 

HoA:-
=====
@result1=(10,20,30,40);
@result2=(50,80,70,60);

%test=(‘case1’=>\@result1,
‘case2’=>\@result2);

testcase 1 what is the first result ?
$test{case1}[0]

which is the best result in testcase 2 ?
max(@{$test{case2}});

HoH:-
=====
%north=(q1=>10,q2=>20,q3=>30,q4=>40);
%south=(q1=>10,q2=>20,q3=>30,q4=>40);
%east=(q1=>10,q2=>20,q3=>30,q4=>40);
%west=(q1=>10,q2=>20,q3=>30,q4=>40);

%sales=(n=>\%north,
s=>\%south,
e=>\%east,
w=>\%west);
What is the sales in east,q2 ?
$sales{e}{q2}

———————————————————
Approach using Named Complex Data Structures:-
==========================================================
%m1=(name=>’arun’,’dept’=>SAN,’loc’=>’pune’);
%m2=(name=>’arun’,’dept’=>SAN,’loc’=>’pune’);
%m3=(name=>’arun’,’dept’=>SAN,’loc’=>’pune’);
%m4=(name=>’arun’,’dept’=>SAN,’loc’=>’pune’);
%m5=(name=>’arun’,’dept’=>SAN,’loc’=>’pune’);

%team=(mem1=>\%m1,mem2=>\%m2,mem3=>\%m3,mem4=>\%m4,
mem5=>\%m5);

%results=(exp=>10,actual=>5);

%project=(pid=>1,
name=>storage,
team=>\%team,
results=>\%results
status=>ongoing);

I need to project1 tem-mem1s name ?
$project{team}{mem1}{name};
Approach using Anon. Complex Data Structures:-
===============================================
$project={pid=>1,
name=>storage,
team=>{m1=>{nam=>’ha’,’dep’=>SAN,’loc’=>’pun’},
m2=>{nam=>’ha’,’dep’=>SAN,’loc’=>’pun’},
m3=>{nam=>’ha’,’dep’=>SAN,’loc’=>’pun’},
m4=>{nam=>’ha’,’dep’=>SAN,’loc’=>’pun’},
m5=>{nam=>’ha’,’dep’=>SAN,’loc’=>’pun’},
},
results=>{actual=>10,expected=>20},
status=>ongoing}

$project->{team}{m1}{name};

 

Approach using Anon. cum Named Complex Data Structures:-
=========================================================
%project=(pid=>1,
name=>storage,
team=>{m1=>{nam=>’ha’,’dep’=>SAN,’loc’=>’pun’},
m2=>{nam=>’ha’,’dep’=>SAN,’loc’=>’pun’},
m3=>{nam=>’ha’,’dep’=>SAN,’loc’=>’pun’},
m4=>{nam=>’ha’,’dep’=>SAN,’loc’=>’pun’},
m5=>{nam=>’ha’,’dep’=>SAN,’loc’=>’pun’},
},
results=>{actual=>10,expected=>20},
status=>ongoing
);
$project{team}{m1}{nam};

Un-named Complex Datastructures:-
=================================
ex1:
$ref=[[1,2,3],[4,5,6],[7,8,9]];

Identify the DS type ? AoA
How to print the value 4 ? $ref->[1][0]
How to print last row ? @{$ref->[2]}

ex2:
$ref=[{a=>1,b=>2},{c=>3,d=>4}];

Identify the DS type ? AoH
How to print the value a ? $ref->[0]{a}
How keys of second hash ? keys(%{$ref->[1]})
ex3:
$ref={
l1=>{a=>[1,2],b=>[3,4]},
l2=>{c=>[5,6],d=>[7,8]}
};

Identify the DS type ? HoHoA
How l1-a-first val ? $ref->{l1}{a}[0]
How l2-c-all the vals ? @{$ref->{l2}{c}}
ex4:
$ref={
n1=>{a=>{1=>2,3=>4} ,b=>{5=>6,7=>8}},
n2=>{c=>{51=>61,71=>81},e=>{11=>21,31=>41}}
}

Indentify the type of DS ? HoHoH
How to print 4 ? $ref->{n1}{a}{3}
How to print keys of “e” ? keys(%{$ref->{n2}{e}});
ex5: $ref={
alpha=>[{a=>1,b=>2},{c=>3,d=>4}],
beta=>[{a=>1,b=>2},{c=>3,d=>4}]
}
Indentify type of DS ? HoAoH
How to print value of alpha-b ? $ref->{alpha}[0]{b}
How many hashes r ther in beta ? scalar @{$ref->{beta}}
ex6: $ref=[arun=>25,basu=>26];

Identify the type of DS ? Array
how to print 25 ? $ref->[1]
ex7: $ref={
a=>{one=>[1,2],two=>[3,4]}},
b=>{one=>[11,21],two=>[31,41]}},
};

Indentify the type DS ? HoHoA
how to print 11 ? $ref->{b}{one}[0]
How to print no elem in a-two ? @{$ref->{a}{two}}

To Debug the Complex Datastructures:-
=====================================
use Data::Dumper;
$ref={
a=>{one=>[1,2],two=>[3,4]}},
b=>{one=>[11,21],two=>[31,41]}},
};

print Dumper($ref);
==========================================================
what is a package ?
– collection of related variables & functions
– they have a separate SYMTABLE maintained
– which avoids name collisions

What is a Module ?
– a filename with .pm extension
– should have a package with the same name

what is the scope of my-variables in a package ?
– is not accessible outside the package

what is the scope of our-variables in a package ?
– is accessible out/inside the package
ex:
in the PL-File:-
================
use mymath;

print “Local = $mymath::a\n”; # not work
print “Global = $mymath::b\n”; # works fine
&mymath::add(); # works fine
we can include the library

method1: use mymath; # prefered
-compile time loading
-variable collision will never occur

method2: require mymath; # not prefered
-runtime loading
-variable collision may occur
How to call the Library Functions ?
– use PerlModuleName;

– PerlPackageName::Functioname;

How to access the Library Variables ?

-VARSYMBOL PerlPackageName::VAR-name
If I include a Perl Module whereis searching for it ?
perl -V

@INC
While choosing the package-name
it should be UNIQUE

perldoc

 

It searches for this module based @INC path
-use Modulename;

if u want to modify the @INC-path specific
u r program

use lib(“path”);
use Modulename;
Every Module has a special set of functions

sub BEGIN{ } – is automatically called when
package is loaded

sub END { } – is automaticallu called when
package is unloaded

 

use – compile Time – most prefered
require – Runtime

 
I have a file named curr.txt
yen 25
dollar 57
euro 87
pounds 80

>>perldoc Exporter
>>u need to define the scope of every var in PM-FILE

Ur module Converter.pm
======================
package Converter;
our %hash;

BEGIN{
open(FH,”curr.txt”);
while(<FH>){
my($key,$value)=split;
$hash{$key}=$value;
}
close FH;
}

sub Convert{
my ($curr,$val)=(shift,shift);
if(exists($hash{$curr})) {
my $temp = $hash{$curr} * $val;
return $temp;
}
else {
return 0;
}
}

1;
In PL-File:-
=============
use Converter;
$name=’dollar’;
$value=100;
$res=Convert($name,$value);
print “$res\n”; # INR: 5700

 
we Copy certain Symbols from the PAckage
to the PL-file with the help

Exporter;

ex: use List::Util;
@EXPORT
@EXPORT_OK
%EXPORT_TAGS

==========================================================
SelfLoader – there is no STUBS
AutoLoader – STUBS are loaded
DynaLoader –

swig.org
OR
perl native

==========================================================
Classes & Objects:-
===================
Since class is a collection
data members
&
member functions

In perl package is a collection of variables & subroutines
so we consider package as a CLASS
package Emp;

our $a;

sub new{
$class=shift;
print “Ctor called\n”;
$ref={code=>undef,name=>undef,salary=>undef};
bless($ref,$class);
}
sub DESTROY{
$self=shift;
print “Dtor called\n”;
}
sub In {
$self=shift;
$self->{code}=shift;
$self->{name}=shift;
$self->{salary}=shift;
}
sub Out{
$self=shift;
print “code = $self->{code}\n”;
print “Name = $self->{name}\n”;
print “Sala = $self->{salary}\n”;
}
package main;
$ptr1=new Emp;
$ptr2=new Emp;
$ptr3=new Emp;
$ptr4=new Emp;
$ptr5=new Emp;
==========================================================
class – package
object – blessed hash-reference
data members – hash keys
member fns – $self=shift
static vars – package variable
static fns – whichever doest have $self=shift;
this pointer – $self
Ctor – sub new { }
Dtor – sub DESTROY { }

==========================================================
Array of Objects:-
===================
use Student;

push(@arr,new Student(‘Arun’,80,78,90));
push(@arr,new Student(‘Basu’,80,78,90));
push(@arr,new Student(‘Chet’,80,78,90));
push(@arr,new Student(‘Dine’,80,78,90));
push(@arr,new Student(‘Hari’,80,78,90));

foreach $ob (@arr)
{
$ob->Print();
}
==========================================================
Inheritance:-
=============
Perl provides us a special variable – @ISA
thru which we can define the path of INHERITANCE

ex:

package Emp; # base class
sub new{}
sub f1{}
sub f2{}

package Manager; # derived class
use Emp;
@ISA=qw(Emp); # define the Inh path

sub new{}
sub f3{}
sub f4{}

sam.pl
——
use Manager;
$m1 = new Manager;
$m1->f1();
$m1->f2();
$m1->f3();
$m1->f4();
from the above example we inherit only SUBROUTINEs
but not the HASH-KEYS ie data members

ex with workaround for inheriting the HASH-KEYS:
package Emp;

sub new{
$class=shift;
$ref={code=>undef,name=>undef,loc=>undef};
bless($ref,$class);
}
sub f1{ print “Base class\n”; }

package Manager;
@ISA=qw(Emp);

sub new{
$class=shift; #workaround
$ref={allow=>undef,team=>undef,%{Emp->new}};
bless($ref,$class);
}
sub f2{ print “Derived class\n”; }

package main;
$ob = new Manager;
print join(“\n”,keys(%$ob));
print “\n”;
$ob->f1();
$ob->f2();
==========================================================
Operator ovearloading:-
———————–

Emp.pm
======
package Emp;

use overload(‘==’ => \&fun); # very important

sub new{
$class=shift;
$ref={name=>shift};
bless($ref,$class);
}
sub fun{
$self=shift;
$args=shift;
if($self->{name} eq $args->{name}){
return 1;
}
else{
return 0;
}
}
1;

package main;
$e1=new Emp(‘arun’);
$e2=new Emp(‘varun’);
if($e1==$e2)
{
print “YEs\n”;
}
else
{
print “No\n”;
}
Private functions:-
——————-
anon subroutine

ie
my $fun=sub{ ….. };
Private Datamembers:-
———————
with the help of CORE Module
ie Hash::Util

 
In Run Time classes
– we can ADD ATTRIBUTES on-demand
– Autovivify the attribute & value at RUN TIME
– Inheritance @ISA=qw(Alpha);
In Compile Time classes
– we need ADD attributes EARLIER itself
– Autovivify the attribute & value at RUN TIME
is impossible
– Inheritance use base(‘Alpha’);

see later: perldoc fields
perldoc base

ex:
package Emp;
use fields qw(code name dept);
sub new
{
my Emp $self = shift;
unless (ref $self) {
$self = fields::new($self);
}
$self->{code}=shift;
$self->{name}=shift;
$self->{dept}=shift;
return $self;
}
sub Print{
$self=shift;
print ” $self->{code}
$self->{name}
$self->{dept}\n”;
}

package main;
$e1=new Emp(1,’arun’,’sales’);
$e1->Print();

 

Class::MethodMaker
is a CPAN libaray which we need to install by
the cpan client
Moose Model classes:-
perldoc Moose
How to know Is that Libaray installed ?
—————————————
1) – perldoc Class::MethodMaker

2) – instmodsh

To Install:-
————-
$ cpan install Class::MethodMaker

OR

$ perl -MCPAN -e “shell”
==========================================================

Regular Expressions:-
=====================

Metachars:
. [] ^ $ ? + * {} | () (?:)

Regex char classes:
\d \w \s \D \W \S \b \B

Regex operators :
$str=~m/REGEX/i;
OR
$str=~/REGEX/i;
$str=~s/REGEX/STATICSTRING/modifiers;
$str=~tr/RANGE/RANGE/;

Regex Memorization:
$str=~s/^(\w+)(\s.*\s)(\w+)$/$3 $2 $1/;

Regex Special vars: (EARLY MATCH)
print $` PREMATCH
print $& MATCH
print $’ POSTMATCH

 
In Perl we do have compile-time Regex:-
=========================================
$str=~qr/$pattern/; # pre-compiled Time

$str=~/$pattern/; # Run Time

 

I have to read the file:-
i have to search for pattern

1) pre-SALES
pre-sales
pre-SAles
2) purch
3) accts

#adding the modifiers within the REGEX:-
========================================

@pattern=qw(pre-(?i)sales purch accts);
open(FH,”data.txt”);

foreach $pat (@pattern)
{
print “$pat list\n”;
print grep(qr/$pat/,<FH>);
seek(FH,0,0);
print “\n”;
}
Regex matched across the MULTI LINE STRING:-
============================================
$str=~/REGEX/sm;

$str=~/REGEX/m;
Non-Memorizing patterns:-
————————-
example for (?:)
example for (?# comments)

@str=(‘hello world of perl’,
‘bye from perl’,
‘new to perl’,
‘hai to perl’);

foreach (@str)
{
if(/^(?:hello|bye|hai)(?#words starting).*/)
{
print “$_ = $1\n”;
}
}

Don’t Replace the ORGINAL STRING:-
———————————-
$str=’hello world’;
$res = $str=~s/[aeiou]//rgi;
print “$str\n”;
print “$res\n”;
Tricks:-
——–
trick1:-
$x=”Bill the cat”;
$x=~s/(.)/$chars{$1}++;$1/eg;

trick2:-
$x = “cat dog house”; # 3 words
while ($x =~ /(\w+)/g)
{
print “Word is $1, ends at position “, pos $x, “\n”;
}

trick3:-
/(?i)yes/; # match ‘yes’ case insensitively
/yes/i; # same thing

 
Look Behind Positive Assertion:-
——————————–
(?=REGEX)

ex:
$str=’i traveled mumbai chennai’;

# costly
if($str=~/delhi/&&$str=~/mumbai/&&$str=~/chennai/)

#cheaper
if($str=~/(?=.*delhi)(?=.*mumbai)(?=.*chennai)/)
{
print “Yes”;
}
else
{
print “No”;
}
Look Ahead Positive Assertion:-
——————————–
(?<=FixedPattern)
Negative Look Behind Assertion:-
——————————–
(?!REGEX)
Negative Look Ahead Assertion:-
——————————–
(?<!REGEX)
$x = “I catch the housecat ‘Tom-cat’ with catnip”;

$x =~ /cat(?=\s)/;

@catwords = ($x =~ /(?<=\s)cat\w+/g);
# matches,
# $catwords[0] = ‘catch’
# $catwords[1] = ‘catnip’
\$x =~ /\bcat\b/; # matches ‘cat’ in ‘Tom-cat’
$x =~ /(?<=\s)cat(?=\s)/; # doesn’t match; no isolated ‘cat’ in
# middle of $x
ex:
$x = “foobar”;
$x =~ /foo(?!bar)/; # doesn’t match, ‘bar’ follows ‘foo’
$x =~ /foo(?!baz)/; # matches, ‘baz’ doesn’t follow ‘foo’
$x =~ /(?<!\s)foo/; # matches, there is no \s before ‘foo’

 

=========================================================
Database Interaction in PERL:-
==============================

step1 : check whether u r perl has DBI.pm
perldoc DBI

step2: check whether u r DBD drivers are installed
perldoc DBD::oracle

OR

use DBI;
print join(“\n”,DBI->available_drivers());
ex1:

use DBI;

$dbh = DBI->connect(‘dbi:ODBC:sample’);

$dbh->do(“delete from emps where name=’777′”);

$sth = $dbh->prepare(“select * from emps”);

$sth->execute();

while(@arr=$sth->fetchrow_array())
{
print “$arr[0] $arr[1] $arr[2]\n”;
}

$dbh->disconnect();

 

 

 

use DBI;

$dbh = DBI->connect(‘dbi:ODBC:sample’,”,”,{AutoCommit=>0});

$dbh->do(“insert into emps values(8,’888′,88)”)
or $dbh->errstr;

$sth = $dbh->prepare(“select * from emps”);
$sth->execute();

$dbh->begin_work();
operation1 or $dbh->roll_back();
operation2 or $dbh->roll_back();
operation3 or $dbh->roll_back();
$dbh->commit();

while(@arr=$sth->fetchrow_array())
{
print “$arr[0] $arr[1] $arr[2]\n”;
}
#$dbh->disconnect();

 

Note:
perldoc DBD::CSV

==========================================================
Ties in Perl:-
==============

use Tie::File;

tie @arr, ‘Tie::File’, “data.txt” or die(“$!”);

$arr[0]=’Now i modified’;

untie @arr;
More Infor:

perldoc perltie

==========================================================
Exception Handling:-
====================
>>on-FLY execution
>>eval { Block };
>>eval is executed in different Thread
with same Lexical Context
>>if the eval is EMPTY is read from “$_”
>>if the eval FAILS is stores the error under
$@
>>eval block is not COMPILED
>>equivalent of throw in perl is => die

Write a perl program
to accept two nos & raise the Divide by ZERO Exception
then if there is an exception DISPLAY APPOR INFO
if there is no exception DISPLAY THE RESULT

ex:

print “Enter the no : “;
chomp($a=<>);
print “Enter the no : “;
chomp($b=<>);

eval
{
if($a==$b) { die(“TYPE1”); }
if($a<$b) { die(“TYPE2”); }
$c=$a/$b;
};

if($@=~/TYPE1/i) { print “Error1\n”; }
elsif($@=~/TYPE2/i){ print “Error2\n”; }
elsif($@=~/divi/i) { print “Error3\n”; }
else { print “Result = “,$c,”\n”; }

 

==========================================================
It is prefered to use
======================
croak instead of -> die
carp instead of -> warn

ex:
use Carp;

sub f4{
print “F4\n”;
croak;
}
sub f3{
print “F3\n”;
f4();
}
sub f2{
print “F2\n”;
f3();
}
sub f1{
print “f1\n”;
f2();
}

print “Main starts\n”;
f1();
print “Main Ends\n”;

==========================================================
caller method:-
===============
__PACKAGE__
__FILE__
__LINE__

package MyTest;

sub fun
{
($pack,$file,$line)=caller;
print “Package name = $pack\n”;
print “Filename = $file\n”;
print “Line num = $line\n”;

print “Package name = “,__PACKAGE__,”\n”;
print “Filename = “,__FILE__,”\n”;
print “Line num = “,__LINE__,”\n”;
}

sub BEGIN
{
fun();
}
package main;
print “MY MAIN STARTS\n”;
print “MY MAIN ENDS\n”;

==========================================================

%INC – will store all the modulenames u perlprogram
is dependent-on

ex:
use DBI;

print join(“\n”,keys(%INC));

==========================================================

To Debug the perl program:-
===========================

step1: $ perl -d programname.pl

step2: List the program with line number
<db> l

step3: u have to set the break points
already there is a break point set to FIRSTLINE
already in RUN MODE
<db> b 10
<db> b sum()

step4: List all the break points
<db> L

step5: Continue the program & stops at next break point
<db> c

step6: Single step mode is ENABLED
<db> s # Will debug the subroutines also
<db> n # Skip debugging the subs

step7: Data Inspection
<db> p $var
<db> p @arr

step8: U want to Modify the Variable value thru Debugger
<db> p $var=10

step9: U can add a HARDWARE watch to a variable
<db> w $a

step10 : AT any point of time u can exit the DEBUGGER
<db> q

Note:
perldoc perldebug

———————————————————-

Singal Handling:-
================

Interrupts in UNIX is SIGNALs
On Unix :- $ kill -l

Signals like SIGKILL & SIGSTOP cannot be TRAPPED/HANDLED

when we execute the perl program
perl automatically captures
signal handler of the process to a special HASH
named %SIG

when is SIGINT is raised ?
cntrl + C
$SIG{‘INT’}=’IGNORE’;
foreach (1..20)
{
print “$_\n”;
sleep(2);
}
$SIG{‘INT’}=’DEFAULT’;
foreach (1..20)
{
print “$_\n”;
sleep(2);
}

Run this program & while it is executing press Cntrl+C

1) $SIG{‘INT’}=’IGNORE’;
2) $SIG{‘INT’}=’DEFAULT’;
3) $SIG{‘INT’}=sub { sub-body };
4) $SIG{‘INT’}=\&fun;

==========================================================
Process mgmt:-
==============

1) if u want to execute a perl program within a perl program

>> do ‘anotherperlprogram.pl’;
>> require anotherperlprogram.pl;

2) If u want to execute a Shell/OS/App Command
which is interactive

system(” Command “);

3) If u wan to execute a shell/OS/App process
which is Noninteractive & u want PERL TO CAPTURE
the output

@arr=`Command`;
OR
@arr=qx(Command);
==========================================================

fork – spwans the process

$pid=fork();
if($pid==0)
{
print “Hello\n”;
}
else
{
print “Bye\n”;
}
waitpid($pid,0);

 

Once

exec – replaces the current process PCB
with its own PCB

 

Shell Scripts:-
===============
#!/bin/bash

shell scripts

exec perl -x $0
#!perl
print “Hello”;
print “hai”;

 

 

 

 

 
———————————————————-
Threads:-
=========

use Thread;
use Threads::shared;

our $a=10;
shared($a);

sub task1{ lock($a);…. }
sub task2{ ….loc($a); }

$t1 = new Thread(\&task1); $t1->join();
$t2 = new Thread(\&task2); $t2->join();

 

Unit Testing : perldoc Test::Unit
perldoc Test