Regular expression in Perl

Walden Systems geeks corner Programming Perl Regular expressions in Perl Rutherford NJ New Jersey NYC New York Bergen County
Perl 5 is a highly capable, feature-rich programming language with over 30 years of development. Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects.

A regular expression is a string of characters that defines the pattern or patterns we are viewing. The syntax of regular expressions in Perl is very similar to what you will find within other regular expression.supporting programs, such as sed, grep, and awk. The basic method for applying a regular expression is to use the pattern binding operators =~ and !~. The first operator is a test and assignment operator. There are three regular expression operators within Perl: match regular expression, substitute regular expression, and transliterate regular expressions.

Match operator

The match operator, m//, is used to match a string or statement to a regular expression. We can use any combination of naturally matching characters to act as delimiters for the expression. For example, m{} and m(), are all valid. We can omit m from m// if the delimiters are forward slashes, but for all other delimiters you must use the m prefix. The entire match expression that on the left of =~ or !~ and the match operator, returns true if the expression matches.

#!/usr/bin/perl

$quote = "try and try again";
if ($quote =~ m[try]) 
{
   print "Matches
";
} else 
{
   print "Does not match
";
}

if ($quote =~ m{try}) 
{
   print "Matches
";
} else 
{
   print "Does not match
";
}
if ($quote =~ /try/) 
{
   print "Matches
";
} else 
{
   print "Does not match
";
}


Substitute operator

The substitution operator, s///, is really just an extension of the match operator that allows us to replace the text matched with some new text. The pattern is the regular expression for the text that we are looking for. The replacement is a specification for the text or regular expression that we want to use to replace the found text with. We can make the substitute operator case insensitive by using the i flag. We can do a global substitution using the g flag.

$string = "Cats are the perfect pet";
print $string ;
$string =~ s/Cats/Dogs/;

print "$string
";


Will output :
Cats are the perfect pet
Dogs are the perfect pet

Translation operator

Translation is similar to substitution, but unlike substitution, translation does not use regular expressions for its search on replacement values. The translation replaces all occurrences of the characters in searchlist with the corresponding characters in replacelist. Standard Perl ranges can also be used, allowing you to specify ranges of characters either by letter or numerical value.

$string = 'The cat in the hat';
$string =~ tr/t/c/;

print "$string
";

$string =~ tr/a-z/A-Z/;
print "$string
";


Will output :
The cac in che hac
THE CAC IN CHE HAC