perloperators

What does =~ do in Perl?


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
}

Solution

  • =~ 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".