Erdnase Erdnase - 1 year ago 94
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?

Answer Source


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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download