为什么 @ 符号在这个 Perl 正则表达式中被转义?
我目前正在讨论 Perls RegExps,我认为总体上理解它。我认为我也掌握了转义字符,即测试反斜杠,可以用 m/\/ 表示,因为反斜杠需要先购买 \ 字符,以告诉 perl 在这种情况下按照其通常的含义来搜索它。
我对下面的代码不明白的是,这个模式匹配以及为什么在使用 @ 符号测试电子邮件地址时使用 (\) (在 if 语句表达式中)。我不知道 @ 是一个需要转义的特殊字符,还是我错过了什么?
#!/usr/bin/perl
EMAIL:
{
print("Please enter your email address: ");
$email = <STDIN>;
if ($email !~ /\@/)
{
print("Invalid email address.\n");
redo EMAIL;
}
else
{
print("That could be a valid email address.");
}
}
I'm currently covering Perls RegExps and on the whole understand it I think. Escaping characters I have also grasped I think, ie testing for a backslash, denoteable by m/\/ in that the backslash needs to be proceeded buy the \ character first to tell perl in this instance to search for it as apposed to it's usual meaning.
What I don't understand with the code below I have is, this pattern match and why (\) is used when testing the email address with @ symbold (in the if statement expression). I'm not aware @ is a special character needing escaping or have I missed something?.
#!/usr/bin/perl
EMAIL:
{
print("Please enter your email address: ");
$email = <STDIN>;
if ($email !~ /\@/)
{
print("Invalid email address.\n");
redo EMAIL;
}
else
{
print("That could be a valid email address.");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它可能被转义以避免被解释为数组印记。这并不是绝对必要的,但这是一个很难打破的习惯。
示例:
产量:
与以下相同:
It's probably escaped to avoid being interpreted as an array sigil. It's not strictly necessary but it's a tough habit to break.
Examples:
yields:
Same with:
@ 不是正则表达式的保留字符,但它是 Perl 的保留字符(它是数组符号)
@ is not a reserved character with respect to regexes, but it is for perl (it's the array symbol)
在 Perl 中,您可以转义任何潜在的正则表达式元字符并保证它是文字。
另外,对于
@
来说,它是数组符号,因此如果有任何可能将其误认为@/
变量,则值得转义。In Perl, you can escape any potential regex metacharacter and be guaranteed it's a literal.
Also, for
@
, it's the array sigil, so if there's any chance of it being mistaken for an@/
variable, it's worth escaping.数组被插入到 Perl 中的双引号字符串和正则表达式中,每个元素之间有特殊变量
$"
(默认情况下是空格字符):我很少使用此功能,但偶尔也会出现方便,例如:
Arrays are interpolated into both double-quoted strings and regexes in Perl, with the special variable
$"
(by default a space character) going between each element:I rarely use this feature, but occasionally it comes in handy, for example: