What does =~ do in Perl?

72,835

Solution 1

=~ is the operator testing a regular expression match. The expression /9eaf/ is a regular expression (the slashes // are delimiters, the 9eaf is the actual regular expression). In words, the test is saying "If the variable $tag matches the regular expression /9eaf/ ..." and this match occurs if the string stored in $tag contains those characters 9eaf consecutively, in order, at any point. So this will be true for the strings

9eaf

xyz9eaf

9eafxyz

xyz9eafxyz

and many others, but not the strings

9eaxxx
9xexaxfx

and many others. Look up the 'perlre' man page for more information on regular expressions, or google "perl regular expression".

Solution 2

The code is testing whether 9eaf is a substring of the value of $tag.


$tag =~ /9eaf/

is short for

$tag =~ m/9eaf/

where m// is the match operator. It matches the regular expression pattern (regexp) 9eaf against the value bound by =~ (returned by the left hand side of =~).


Operators, including m// and =~, are documented in perlop.

Regular expressions (e.g. 9eaf) are documented in perlre, perlretut.

Share:
72,835
Invictus
Author by

Invictus

Updated on January 25, 2020

Comments

  • Invictus
    Invictus about 4 years

    I guess the tag is a variable, and it is checking for 9eaf - but does this exist in Perl?

    What is the "=~" sign doing here and what are the "/" characters before and after 9eaf doing?

    if ($tag =~ /9eaf/)
    {
        # Do something
    }
    
  • Invictus
    Invictus about 12 years
    You mean if there is a space in between it does not work... for example... 9sssbt yyuuiihh 88880099 9eaf 888hhjjj nnmmmm. Will the above logic for this string???
  • ikegami
    ikegami about 12 years
    No, m// is the <strike>operation</strike>operator testing the regex. =~ simply tells m// (and s/// and tr//) which variable to test against.
  • ikegami
    ikegami about 12 years
    No, /9eaf/ is not the regular expression. /9eaf/ is the match operator. 9eaf is the regular expression.