加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么括号在分配此正则表达式匹配时如此重要?

发布时间:2020-12-14 05:56:33 所属栏目:百科 来源:网络整理
导读:我有一段代码: $s = "sekar kapoor";($name) = $s =~ /([Ss]*)/;print "$namen"; # Output is 'sekar kapoor' 如果在第二行代码中删除了括号,则在变量$name中: $name = $s =~ /([Ss]*)/; # $name is now '1' 我不明白为什么它会像这样.任何人都可以解
我有一段代码:

$s = "<sekar kapoor>";
($name) = $s =~ /<([Ss]*)>/;
print "$namen";               # Output is 'sekar kapoor'

如果在第二行代码中删除了括号,则在变量$name中:

$name = $s =~ /<([Ss]*)>/;   # $name is now '1'

我不明白为什么它会像这样.任何人都可以解释为什么会这样吗?

解决方法

在您的第一个示例中,您在左侧有一个列表上下文(您使用了括号);在第二个你有一个标量上下文 – 你只有一个标量变量.

请参阅Perl docs for quote-like ops,匹配列表上下文:

If the /g option is not used,m// in
list context returns a list consisting
of the subexpressions matched by the
parentheses in the pattern,i.e.,($1
,$2,$3
…).
(Note that here $1
etc. are also set,and that this
differs from Perl 4’s behavior.)
When there are no parentheses in the
pattern,the return value is the list
(1) for success. With or without parentheses,an empty list is returned upon failure.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读