Day 4

Scope of variables in PERL:
All the variables are by default global variables.
To limit the scope of variable within a namespace use the key word “my”.
To ensure all variables are declared with my keyword use “use strict” at the beginning of the program.

Private variables in PERL:
• Any variable defined with the keyword my to make it private is released as soon as the code block in which it was defined is terminated
• You can have private and global variables with the same name, and they are treated differently by the compiler:
$num1=6;
sub something
{ my $num1; # different variable
statements…}
• Both $num1s are treated as different in this case
We can use “local” keyword and its makes variable accessible in current block.
#====================================================================================#Example1: Scope of variable Demo in PERL
#====================================================================================$v1=1;
print "1. $v1\n";
{
                $v1=2;
                print "2. $v1\n";
}
print "3. $v1\n";

#use strict keyword to ensure that all variables are declared with my keyword
print "using my keyword for declaring a variable\n";
$v2=2;
print "1. $v2\n";
{
                my $v2=3;
                print "2. $v2\n";
}
print "3. $v2\n";
#====================================================================================
#Example2: Demo for functions and scope of variable in PERL
#====================================================================================
sub calc
{
                my($v1,$v2)=@_;
                my $sum=$v1+$v2;
                return $sum;
}
$total=calc(10,20);
print "Total:$total\n";
print "Sum:$sum\n";
#====================================================================================
Regular Expression in PERL: Used to search a string with specific format.

Meta characters in PERL: ^ $ . []
^pattern -> The line starting with pattern
pattern$ -> The line ending with pattern
^pattern$ -> The line having only pattern
^$ -> Empty Line
. -> Any single Character
^.. -> Starting with any 2 characters
.$ -> Ending with any one character
[abT] -> matching any single character a or b or T.
[^abt] -> not matching single character a or b or T. If there any other character other than a b T, the result will show the o/p.

Quantifiers in PERL:
Greedy
Nongreedy
Allowed numbers for a match
?
??
0 or 1 time
+
+?
1 or more times
*
*?
0 or more times
{i}
{i}?
exactly i times
{i,}
{i,}?
i or more times
{i,j}
{i,j}?
at lease i times and at most j time

Bind Operators in PERL:
=~ equal to operator
!~ not equal to operator
#====================================================================================
#Example3: Regular Expressions in PERL
#====================================================================================

$IP="Perl support dbi module";
# =~ is the bind operator for the equal to comparison of the pattern

if($IP =~ /dbi/)
{
                print "Matched!\n";
}
else
{
                print "No Match\n";
}
#i is used to pattern ignore the cases
if($IP =~ /DBI/i)
{
                print "Matched!\n";
}
else
{
                print "No Match\n";
}
#using ^ anchor meta character
if($IP =~ /^perl/)
{
                print "Matched!\n";
}
else
{
                print "No Match\n";
}
if($IP =~ /^perl/i)
{
                print "Matched!\n";
}
else
{
                print "No Match\n";
}

while(1)
{
                print "Enter a url :";
                chomp($url=<>);
               
                if($url =~ /^https/i)
                {
                                print "Valid URL!!\n";
                                last;
                }
                else
                {
                                print("Invalid URL\n");
                                print("Please try again\n");        
                }
}

while(1)
{
                print "Enter your input pattern:\n";
                chomp($i=<>);
                if($i =~ /^[^abT]/) #matches with the string which starts with any character except a, b or T
                {
                                print "Matched!\n";
                                last;
                }
                else
                {
                                print("Not Matched \n");
                                print("Please try again\n");        
                }
}

while(1)
{
                print "Enter your name:";
                chomp($Fname=<>);
                if($Fname =~ /[Rr]avi/)
                {
                                print "Matched $Fname\n";
                                last;
                }
                else
                {
                                print "Not matched\n";
                }
}
#====================================================================================
\ - a form of a "quote" character
| - alternation, used for "or'ing"
() - grouping matched elements
[] - character class

The first character, "\", is used in combination with special letters to take away their special meaning. E.g.:
\. will match a period
\$ will match a dollar sign
\^ will match a caret
\\ will match a backslash

The pipe symbol "|" is used to provide alternatives:
/good|bad/ will match either "good vibes" or "bad karma".
The parentheses group matched elements, so
/(good|bad) example/
is the same as searching simultaneously for /good example/ or /bad example/
Without the ()'s, this would be the same as searching simultaneously for /good/ or /bad example/
The square brackets indicate a class of characters, so /^[abcd]/ would match any strings beginning with the letters a through d. This can also be written in shorthand as /^[a-d]/.

 Special Backslash Combination Characters in PERL:

The backslash character is also used in conjunction with non-special characters to give them a special meaning. For instance

\t is a tab character
\n is a newline character
\d is any digit equivalent to [0-9]
\D is any non-digit equivalent to [^0-9]
\s is a whitespace character equivalent to [“ ”]
 \S is any non whitespace character equivalent to [^“ ”]
\w is any alphabet equivalent to [a-zA-Z]
\W is any non-alphabet equivalent to [^a-zA-Z]
#============================================================================
#Use file handler in PERL and open a file
# Read i/p file
#search pattern s/pune/bangalore/ and ignore the case
#writes the output to the new file
#============================================================================

if(-f "test1.txt")
{
                open(IFH,"<test1.txt");
                print "Opening the input file\n";
}
else
{
                print "test1.txt does not exists\n";
}

if(-f "test2.txt")
{
                open(OFH,">test2.txt");              
                print "Opening the output file\n";
}
else
{
                print "test2.txt does not exists\n";
}

while(<IFH>)
{
                if(/pune/)
                {
                                print "Pattern matched found at line no. $. \n";
                                $_ =~ s/pune/bangalore/i;
                                print OFH "$_";
                }
}

close(IFH);
close(PFH);
#============================================================================

Alternate Pattern Search in PERL:
#============================================================================
#Alternate Pattern Search in PERL using “|”
#grouping using () in PERL
#============================================================================
while(<>)
{
                chomp;
                if ($_=~ /unix|linux/)
                {
                                print "True using Alternate Pattern: $_ Matched\n";
                               
                }
                else
                {
                                print "False: $_ No Match\n";
                }

                if ($_=~ /(unix|linux).os/)
                {
                                print "True using Alternate & grouping Pattern: $_ Matched\n";
                                last;
                }
                else
                {
                                print "False: $_ No Match\n";
                }
}
#============================================================================
#Group Alternatives: Perl places each grouping data under $1 $2 $3 and so on
$var1="testing";

if($var1=~ /((T|t)est(ing|er))/)
{
                print "$1\t$2\t$3\t$4\n";
}
#============================================================================
while (<>)
{
                chomp;
                if($_=~ /ma{2}n/)
                {
                                print "Matched\n";
                                last;
                }
                else
                {
                                print "Patern not matched\n"
                }
}
#============================================================================
<<Output;
D:\perl\day4>perl 5.pl
linuxuos
True using Alternate Pattern: linuxuos Matched
True using Alternate & grouping Pattern: linuxuos Matched
testing t       ing
Output

Running a UNIX command in perl:
system(“grep sales IPfile”);
or
print ` grep sales IPfile`;
or
$v1=` grep sales IPfile`;

#============================================================================
#To print the lines starting and ending with a blank space in PERL
#============================================================================
open(FH,"test1.txt") or die($!);
while(<FH>)
{
                chomp;
                if($_ =~ /\s$/ )
#             if($_ =~ /[[:space:]]$/ )
                {print "blank space at the end of line $.\n";}
                if($_ =~ /\s$/ )
#             if($_ =~ /^[[:space:]]/)
                {print "blank space at the begining of the line $. \n";}
               
}
close(FH);

#============================================================================
#read a file and store the numbers, alphabets and special characters in separate arrays in PERL
#============================================================================
open(FH,"test1.txt") or die($!);
@n=();
@a=();
@s=();
@line=();
while(<FH>)
{
                chomp;
                @line=split("",$_);
                #print "@line\n";
                for(@line)
                {
                                #print "$_\n";
                                if($_ =~ /[[:digit:]]/)
                                {push(@n,$_);}
                                if($_ =~ /[[:alpha:]]/)
                                {push(@a,$_);}
                                if($_=~ /[^[:alnum:]]/)
                                {push(@s,$_);}
                }
}
close(FH);

print "Numbers: @n \n";
print "Alphabets: @a \n";
print "Special Characters: @s \n";
#============================================================================
#Checking/validating the date format in PERL
#============================================================================
print "Enter the date in DD-MM-YYYY format:\n";
while(<>)
{
                chomp;
                if($_ =~ /((([0][1-9])|([1-2][0-9])|([3][0-1]))-([0-9][1-2])-(\d{4}))/)
                {
                                print "Valid Format!\n";
                               
                }
                else
                {
                                print "invalid Format!\n";
                }
}
#============================================================================

TR command in PERL:
syntax:
$inputvariable=tr (/oldpattern/newpattern/);
$count=($inputvariable=tr (/oldpattern/newpattern/));
$count will give the total number of replacements.
tr/oldpattern/newpattern/c
Here c is used for compliment i.e. to reverse the search criteria.
Package: Collection of data members, functions
Default package is main package.

package <name of the package>;
variable decalaration
function definition
.
.
.
#============================================================================
#Package handling in perl
#============================================================================
#File(9.pl) containing package definition
#============================================================================
$v1=1;

package AB;
$v1=2;
sub hello
{
                print "Hello function from package: ",__PACKAGE__,"\n";
}
print "From",__PACKAGE__,"\$v1:$v1\n";#displaying variable $v1 from package AB
print "From",__PACKAGE__,"\$v1:$main::v1\n";#displaying variable $v1 from package main in package AB
package main;
print "From",__PACKAGE__,"\$v1:$v1\n";#displaying variable $v1 from package AB
AB::hello();
 # for Error handling purpose
sub AUTOLOAD
{
                print "Error Details: $AUTOLOAD\n";
}

package Fax;

sub Display
{
                print "Virtual memeory statsus..\n";
                print `dir`;
                print "Exit from :",__PACKAGE__," From $0 file..\n";
}
#============================================================================
#Linking the package file with other file and calling its function
#============================================================================
require '9.pl';
Fax::Display();

Module:
è One module can have only one package.
è package name is same as file name
è file name end with .pm
è Module should end with positive integer
è using module I program: use <module name>;
#============================================================================
#defining Module
#============================================================================
package Fax;
$var=1;
sub display
{
                print "List of files\n";
                print `dir`;
}
1
#============================================================================
#Using Module
#============================================================================
use Fax;
Fax::display();
print "$FAX::var\n";

awk -F: '/root/{print}/' IP1
root:x:0:0:root:/root:/bin/bash
cat >p1.sh
BEGIN{
FS=":"
}
/root/{print}
END
{
print "Thank You!!"
}
#============================================================================

No comments:

Post a Comment