
The built in Perl operator =~ is used to determine if a string contains a string, like this.
if ("foo" =~ /f/) {
print "'foo' contains the letter 'f' \n";
}
The !~ operator is used to determine if a string does not contains a string, like this.
if ("foo" !~ /a/) {
print "'foo' does not contain the letter 'a' \n";
}
Using variables
Often, variables are used instead of strings.
my $foo = "bar";
my $letter = "a";
if ($foo =~ /$letter/) {
print "$foo contains the letter $letter \n";
}
Multiple comparisons
Let's say you want to check if $foo contains two (or more) letters.
my $foo = "bar";
my $first_letter = "a";
my $second_letter = "b";
if ($foo =~ /$first_letter|$second_letter/) {
print "$foo contains the letter $first_letter or the letter $second_letter \n";
}
Or to check if $foo or $bar contain the letter "a".
my $foo = "hello";
my $bar = "world";
my $letter = "a";
if (grep{ $_ =~ /$letter/} ($foo, $bar)) {
print "The \$foo or \$bar variable contains the letter $letter \n";
}
Exact match (no white space)
In this example, the if statement would evaluate to true, because $foo does contain the letter a or the letter b, even though these contain white space. The following regular expression will account for this, and only return true when $foo contains a whitespace followed by the letter a and followed by a whitespace, or a whitespace followed by the letter b and a whitespace.
my $foo = "bar";
my $first_letter = " a ";
my $second_letter = " b ";
if ($foo =~ /^($first_letter|$second_letter)$/i) {
print "$foo contains the letter $first_letter or the letter $second_letter \n";
}
Did you find this article helpful?
If so, consider buying me a coffee over at