Perl shell 命令无法匹配 @ 符号

Perl shell command cannot match @ symbol

我正在尝试使用 perl 编写 shell 命令,对字符串进行非常基本的检查,看它是否看起来像电子邮件地址。下面的最小可重现示例:

# perl --version v5.28.1
perl -E 'exit 1 if "you@example.com" !~ /@/' || echo 'failed'

以上输出failed。我知道 @ 符号用于表示 perl 中的数组,但在搜索之后显然不需要转义。即使我用反斜杠转义它,结果也是一样的。

接下来的问题是,为什么 sh 运行 perl 正则表达式不能匹配 @ 符号?还是我还缺少其他东西?

固特异在 corner shop 有售,为什么还要用马车轮子?

use Email::Valid;
my $address = Email::Valid->address('you@example.com');
exit $address ? 1 : 0;

你原来的问题是引用问题。但是你现在知道了,我从评论中估计出来了。

@Mat 在问题下方的评论中建议的 运行 命令后,这里的问题很明显。

$ perl -wE 'print "you@example.com\n";'
Possible unintended interpolation of @example in string at -e line 1.
Name "main::example" used only once: possible typo at -e line 1.
you.com

正在匹配的字符串使用了双引号,导致它被插入。插值将 @example 转换为数组引用但将其删除,因为它未定义。

因此,原问题中的正则表达式无法匹配电子邮件,因为在字符串插值过程中,部分正则表达式被删除了。