我最近看到了一个不熟悉 Perl 的人写的代码。
他想比较两个字符串是否相等,但不知道eq
运营商,所以他使用了 =~
像这样:
my $str1 = 'foobar';
my $str2 = 'bar';
if ( $str1 =~ $str2 ) {
print "strings are equal\n";
}
另一个片段是
if ( $str1 =~ "foo" ) {
print "string equals 'foo'\n";
}
当然,它应该简单地读为
$str1 eq $str2
和 $str1 eq "foo"
以避免误报。我通过
Deparse
运行代码它说一切正常:$ perl -MO=Deparse -e 'use strict;
use warnings;
my $str1="foobar";
my $str2="bar";
$str1 =~ $str2;
$str1 =~ "bar";'
use warnings;
use strict;
my $str1 = 'foobar';
my $str2 = 'bar';
$str1 =~ /$str2/;
$str1 =~ /bar/;
-e syntax OK
我翻阅了docs ,但据我了解
情况如下:
m/pattern/
. m
和您选择的分隔符而不是 /
(但请注意 '
和 ?
具有特殊含义)m
但是分隔符必须是 /
. 但显然 Perl 理解
$str1 =~ "foo"
如 $str1 =~ m/foo/
虽然没有 m
存在。这是为什么?我原以为这是一个语法错误。
最佳答案
I'd expected that to be a syntax error.
引用
=~
的文档在 perlop ,If the right argument is an expression rather than a search pattern, substitution, or transliteration, it is interpreted as a search pattern at run time.
But apparently Perl understands
$str1 =~ "foo"
as$str1 =~ m/foo/
although nom
is present. Why is that?
为什么不?我想不出不拥有的理由
=~
如果其 RHS 上没有匹配、替换或音译运算符,则暗示匹配运算符。我会用$s =~ /foo/
超过
$s =~ "foo"
但我用过
$s =~ $re
特别是当
$re
的值是qr//
编译的模式.
关于regex - 为什么 `$str1 =~ "foo "` recognized as ` $str1 =~ m/foo/`(而不是语法错误)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39498206/