为什么 `$str1 =~ "foo"` 被识别为 `$str1 =~ m/foo/`(而不是语法错误)? [英] Why is `$str1 =~ "foo"` recognized as `$str1 =~ m/foo/` (and not a syntax error)?
问题描述
我最近看到了一个不熟悉 Perl 的人写的代码.他想比较两个字符串是否相等,但不知道eq
操作符,所以他使用 =~
像这样:
my $str1 = 'foobar';我的 $str2 = 'bar';如果( $str1 =~ $str2 ){print "字符串相等\n";}
另一个片段是
if ( $str1 =~ "foo" ) {打印 "字符串等于 'foo'\n";}
当然它应该简单地读取 $str1 eq $str2
和 $str1 eq "foo"
以避免误报.
我通过 Deparse
运行代码,它说一切正常:
$ perl -MO=Deparse -e '使用严格;使用警告;我的 $str1="foobar";我的 $str2="bar";$str1 =~ $str2;$str1 =~ "bar";'使用警告;使用严格;我的 $str1 = 'foobar';我的 $str2 = 'bar';$str1 =~/$str2/;$str1 =~/bar/;-e 语法正常
我浏览了文档,但根据我的理解情况如下:
- 一般语法是
m/pattern/
. - 要么使用
m
和您选择的分隔符而不是/
(但请注意'
和?
有特殊含义) - 或者去掉
m
,但是分隔符必须是/
.
但显然 Perl 将 $str1 =~ "foo"
理解为 $str1 =~ m/foo/
尽管没有 m
存在.这是为什么?我原以为这是一个语法错误.
我原以为这是一个语法错误.
在perlop中引用=~
的文档,><块引用>
如果正确的参数是表达式而不是搜索模式、替换或音译,则在运行时将其解释为搜索模式.
<小时><块引用>
但显然 Perl 将 $str1 =~ "foo"
理解为 $str1 =~ m/foo/
尽管没有 m
存在.这是为什么?
为什么不呢?如果 RHS 上没有匹配、替换或音译运算符,我想不出不让 =~
暗示匹配运算符的理由.我会用
$s =~/foo/
结束
$s =~ "foo"
但我用过
$s =~ $re
特别是当$re
的值是由qr//
编译的模式时.
I recently saw code from someone who's not familiar with Perl.
He wanted to compare two strings for equality but didn't know about
the eq
operator, so he used =~
like this:
my $str1 = 'foobar';
my $str2 = 'bar';
if ( $str1 =~ $str2 ) {
print "strings are equal\n";
}
Another snippet was
if ( $str1 =~ "foo" ) {
print "string equals 'foo'\n";
}
Of course it should simply read $str1 eq $str2
and $str1 eq "foo"
to avoid false-positives.
I run the code through Deparse
and it said everything is ok:
$ 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
I looked through the docs, but from my understanding the situation is as follows:
- The general syntax is
m/pattern/
. - Either use
m
and a delimiter of your choice instead of/
(but be aware that'
and?
have special meaning) - Or leave off the
m
but then the delimiter must be/
.
But apparently Perl understands $str1 =~ "foo"
as $str1 =~ m/foo/
although no m
is present. Why is that? I'd expected that to be a syntax error.
I'd expected that to be a syntax error.
Quoting the documentation for =~
in 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?
Why not? I can't think of a reason not to have =~
imply a match operator if there's no match, substitution or transliteration operator on its RHS. I'd use
$s =~ /foo/
over
$s =~ "foo"
but I have used
$s =~ $re
Especially when the value of $re
is a pattern compiled by qr//
.
这篇关于为什么 `$str1 =~ "foo"` 被识别为 `$str1 =~ m/foo/`(而不是语法错误)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!