简体   繁体   English

Perl 匹配运算符 =~

[英]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. ("Johnson" =~ /son/ )返回 true 但(/son/ =~ "Johnson")返回 false。 What is the exact reason?确切的原因是什么? Why =~ operator behaves differently when the operands are interchanged?为什么 =~ 运算符在操作数互换时表现不同?

STRAIGHT OUTTA DOCS:直接退出文档:

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?这个 Perl 语句是关于什么的? "Hello World" is a simple double-quoted string. "Hello World"是一个简单的双引号字符串。 World is the regular expression and the // enclosing /World/ tells Perl to search a string for a match. World是正则表达式, //封闭的/World/告诉 Perl 在字符串中搜索匹配项。 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.在我们的例子中, World匹配"Hello World"中的第二个单词,所以表达式为真。

Please read http://perldoc.perl.org/perlretut.html请阅读http://perldoc.perl.org/perlretut.html


Now in your example "Johnson" =~ /son/ matches because RHS of =~ (which is son) is found in LHS (Johnson).现在,在您的示例中, "Johnson" =~ /son/匹配,因为在 LHS(Johnson)中找到了=~ (即儿子)的 RHS。 In case of /son/ =~ "Johnson" RHS (Johnson) is not found in LHS (son).如果/son/ =~ "Johnson" RHS (Johnson) 在 LHS (son) 中找不到。

Well... because the =~ operator binds a scalar expression, to a pattern match.嗯...因为 =~ 运算符将标量表达式绑定到模式匹配。

So it states the order in which the arguments need to be given.所以它说明了需要给出参数的顺序。 Your second (/son/ =~ "Johnson") uses Johnson as pattern... and that one is not hit, thus false.你的第二个(/son/ =~ "Johnson")使用 Johnson 作为模式......并且那个没有被击中,因此是错误的。

See binding operators: https://users.cs.cf.ac.uk/Dave.Marshall/PERL/node87.html请参阅绑定运算符: https : //users.cs.cf.ac.uk/Dave.Marshall/PERL/node87.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM