Friday, February 25, 2011

Regular expressions in Perl

Regular expressions are a syntax that helps in string type data manipulation, like pattern matching, string selections and string replacements.

Following is a simple example showing how to use regular expressions in Perl.

#!/usr/bin/perl

print "content-type: text/html \n\n";

$string = "Hello And Good Morning James";

if ($string =~ m/Good/) # m before the first slash is the "match" operator, returns true if "Good" is found in the string.
{
 print "Good found in $string\n";
}

if ($string =~ m/^Hello/) # ^ after the first slash signifies matching to be done from the starting of the string, returns true if "Hello" is found at the starting of the string. 
{
 print "Hello found at the starting of $string\n";
}

if ($string =~ m/James$/) # $ before the last slash signifies matching to be done from the ending of the string, returns true if "James" is found at the end of the string. 
{
 print "James found at the end of $string\n";
}

if ($string =~ m/good/i) # i after the last slash signifies matching to be done ignoring the case, returns true if "good" in any case (upper, lower, toggle, sentence) is found in the string.
{
 print "good found in $string\n";
}

$string =~ m/Hello And(.*)James/; # (.*) in the pattern returns the missing/ unknown characters from the string in a special variable

$fetched_string = $1; # $1 here represents the special variable holding the returned missing/ unknown characters from the previous regular expression.
print "$fetched_string\n";

$string =~ s/Morning/Evening/; # s before first slash is "substitute" operator, here if "Morning" is present in the string it will be replaced with "Evening". 
print "$string\n";

Output:
-------
Good found in Hello And Good Morning James
Hello found at the starting of Hello And Good Morning James
James found at the end of Hello And Good Morning James
good found in Hello And Good Morning James
 Good Morning
Hello And Good Evening James