Bootstrap FreeKB - Perl (Scripting) - Variable contains (=~) or does not contain (!~)
Perl (Scripting) - Variable contains (=~) or does not contain (!~)

Updated:   |  Perl (Scripting) articles

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 Buy Me A Coffee



Comments


June 28 2022 by akaodin
How do you check if a string contains a '+' or '*' with the =~ operator. I am beginning to think it is impossible and have resorted to index( $str, '+' );

Add a Comment


Please enter 4d135f in the box below so that we can be sure you are a human.