Erdnase Erdnase - 5 months ago 39
Perl Question

Perl Match Operator =~

This is a very basic question but I am not able to find any proper documentation explaining this behaviour.

("Johnson" =~ /son/ )
returns true but
(/son/ =~ "Johnson")
returns false. What is the exact reason? Why =~ operator behaves differently when the operands are interchanged?



The simplest regexp is simply a word, or more generally, a string of characters. A regexp consisting of a word matches any string that contains that word:

"Hello World" =~ /World/;  # matches 

What is this Perl statement all about? "Hello World" is a simple double-quoted string. World is the regular expression and the // enclosing /World/ tells Perl to search a string for a match. The operator =~ associates the string with the regexp match and produces a true value if the regexp matched, or false if the regexp did not match. In our case, World matches the second word in "Hello World" , so the expression is true.

Please read

Now in your example "Johnson" =~ /son/ matches because RHS of =~ (which is son) is found in LHS (Johnson). In case of /son/ =~ "Johnson" RHS (Johnson) is not found in LHS (son).