Perl Regular Expressions

Regular expression is simply a string of characters that is used to define the pattern(s) you are viewing. The basic method to apply a regular expression is to use the pattern binding operators =~ and !~. Here, the first operator is the test and assignment operator. There are following three types of regular expression available in perl:

  • m// - Match Regular Expression
  • s/// - Substitute Regular Expression
  • tr/// - Transliterate Regular Expression

Here, the forward slashes (/) in each case, basically acts as the delimiters for the regular expression that you are specifying.

Perl Regular Expression Example

Here is an example, demonstrates the concept and use of regular expression in perl:

#!/usr/bin/perl

$bar = "This is foo and again foo";

if ($bar =~ /foo/)
{
   print("First time is matching\n");
}
else
{
   print("First time is not matching\n");
}

$bar = "foo";

if ($bar =~ /foo/)
{
   print("Second time is matching\n");
}
else
{
   print("Second time is not matching\n");
}

When the above code is executed, it will produce the following output:

First time is matching
Second time is matching

Perl Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋