在Perl/Tk代码中,我发现了一个条件语句如下
if (s/^\+//)
{
#do something
}
elsif (/^-/)
{
#do another thing
}
Run Code Online (Sandbox Code Playgroud)
似乎已经完成了一些模式匹配.但我无法理解.任何人都可以帮我理解这种模式匹配吗?
sim*_*que 11
它们都是正则表达式.你可以在perlre和perlretut上阅读它们.你可以在http://www.rubular.com上玩它们.
他们都含蓄地做了些什么$_.您的代码行可能有一个while或foreach几乎没有循环变量.在那种情况下,$_成为循环变量.例如,它可能包含正在读取的文件的当前行.
$_包含一个+(加号)符号作为字符串开头的第一个字符,#do somehting.-(减号), #do another thing.在情况1.它也+没有任何东西替换该标志(即删除它).它不会删除-2.但是.
让我们看看YAPE :: Regex :: Explain的解释.
use YAPE::Regex::Explain;
print YAPE::Regex::Explain->new(qr/^\+/)->explain();
Run Code Online (Sandbox Code Playgroud)
这里是.在我们的案例中并没有真正帮助,但仍然是一个很好的工具.请注意,(?-imsx和)部分是Perl暗示的默认值.除非你改变它们,它们总是在那里.
The regular expression:
(?-imsx:^\+)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
\+ '+'
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
更新:正如Mikko L在评论中指出的那样,你应该重构/改变这段代码.虽然它可能会做到它应该做的事情,但我相信让它更具可读性是一个好主意.谁写了它显然并不关心你作为后来的维护者.我建议你这样做.您可以将其更改为:
# look at the content of $_ (current line?)
if ( s/^\+// )
{
# the line starts with a + sign,
# which we remove!
#do something
}
elsif ( m/^-/ )
{
# the line starts witha - sign
# we do NOT remove the - sign!
#do another thing
}
Run Code Online (Sandbox Code Playgroud)
这些是正则表达式,用于模式匹配和替换.
你应该阅读这个概念,但至于你的问题:
s/^\+//
Run Code Online (Sandbox Code Playgroud)
如果字符串以加号开头,则删除该加号("s"表示"替换"),并返回true.
/^-/
Run Code Online (Sandbox Code Playgroud)
如果字符串以减号开头,则为True.