1. Perl
  2. Operators
  3. here

=~ - Pattern Matching Operators

=~ is the pattern matching operator. It is used when executing pattern matching and replacement with Regular Expressions.

Pattern Matching

Pattern matching operators are used with regular expressions.

# Pattern Matching Operators
$message =~ /eat/

If the $message matches the regular expression, the pattern matching operator returns a true value.

Negate Pattern Matching Operator

To check if strings don't match regular expressions, you use negate pattern matching operators.

$message !~ /You/

If the $message does not match the regular expression, the negate pattern matching operator returns a true value.

Replacement

You can replace strings with pattern matching operators and regular expressions.

# s/RegularExpression/ReplaceString/
$message =~ s/orange/banana/;

If the $message matched the regular expression, it is replaced with the specifed string.

Example

Examples of regular expressions and pattern matching operators.

use strict;
use warnings;

my $message = 'I eat an orange.';
print "\$message:$message\n\n ";

print "1: Check if the string contains eat.\n";
if ($message =~ /eat/) {
  print "\$message contains eat.\n\n";
}

print "2: Check if the string contains You.\n";
if ($message !~ /You/) {
  print "\$message does not contain You.\n\n";
}

print "3: Replace orange in the string with banana.\n";
$message =~ s/orange/banana/;

print "$message\n";

The output:

$message:I eat an orange.

 1: Check if the string contains eat.
$message contains eat.

2: Check if the string contains You.
$message does not contain You.

3: Replace orange in the string with banana.
I eat an banana.

Related Informatrion