Q1. Read variable values from a string
A1. Example read Name and Age value from following string
Name=Manoj, Age=31
#!c:/perl/bin
my $str = "name=manoj, age=31"; #whatever variable str want to fetch put it in (), it will redirect to special variables $1....$9
if($str=~/name=(.*),age=(.*)/g) # Each bracket will match and redirect output to default variable starts from $1 to $9
{
print "nam is: $1 \n, Age is : $2\n";
}
Note:
$x = 'the cat and rat in the hat';
if( $x =~ /^(.*)at(.*)$/) # The first quantifier (.*) grabs as much of the string as possible while still having the regex match.
# The second quantifier .* has no string left to it, so it matches 0 times
{
print "$1 , $2 , $3\n";
}
output: the cat and rat in the h , ,
if( $x =~ /^(.*)at(.*)at(.*)at(.*)$/)
{
print "$1 , $2 , $3\n";
}
output: the c, and r, in the h
Link : http://perldoc.perl.org/perlrequick.html
Q2. Write a reg ex to match either pattern1 Or pattern2
A2.
for getting "yes" or "yet" use -->
/(yes|yet)/
OR
/ye(s|t)/
OR
/ye[st]/
$x="yes I am here";
$y="yet, I am here";
if($y=~/ye(s|t)/g)
{
print "\nFOUND !\n";
}
Q3. Replace a character in a string, count its occurrence, delete it.
A3. point to be noted that tr changes in original string itself. So make a copy of it before use.
#!C:\perl\bin
my $str="012 345543 210 012 3";
my $newstr= $str;
my $newstr1= $str;
my $newstr2= $str;
my $ret=$newstr =~s/012/abc/g; #substitute
print "$ret :$newstr";
$ret=$newstr1 =~tr/012/abc/;
print "\n $ret : $newstr1";
$ret=$newstr2 =~tr/012//;
print "\n $ret : $newstr2";
$ret=$newstr2 =~tr/012//d; # Use /d to delete
print "\n $ret : $newstr2";