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

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 built in Perl operator =~ is used to determine if a string 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";
}

 


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";
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |