根据
perlretut
… in scalar context,
$time =~ /(\d\d):(\d\d):(\d\d)/
returns a true or false value. In list context,however,it returns the list of matched values($1,$2,$3)
.
但是,如果在regexp中没有捕获组时模式匹配,我找不到列表上下文中返回内容的解释.测试表明它是list(1)(单个元素,整数1). (辅助问题 – 它总是这样,它在哪里定义?)
这使我很难做到我想要的:
if (my @captures = ($input =~ $regexp)) { furtherProcessing(@captures); }
我希望在匹配时调用FurtherProcessing,并将任何捕获的组作为参数传递.当$regexp不包含任何捕获组时问题就出现了,因为我希望在没有参数的情况下调用FurtherProcessing,而不是使用上面发生的值1.我无法测试(1)作为特殊情况,就像这样
if (my @captures = ($input =~ $regexp)) { shift @captures if $captures[0] == 1; furtherProcessing(@captures); }
因为在这种情况下
$input = 'a value:1'; $regexp = qr/value:(\S+)/;
@captures中有一个捕获的值,看起来与$regexp匹配但没有捕获组时得到的值相同.
有办法做我想要的吗?
您可以使用
$#+
查找上次成功匹配中有多少组.如果那是0,则没有组,你有(1). (是的,如果没有组,将始终是(1),如
perlop中所述.)
所以,这将做你想要的:
if (my @captures = ($input =~ $regexp)) { @captures = () unless $#+; # Only want actual capture groups furtherProcessing(@captures); }
请注意,$#计算所有组,无论它们是否匹配(只要整个RE匹配).那么,“hello”=〜/ hello(world)?/将返回1组,即使该组不匹配(@captures中的值将是undef).
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。