简体   繁体   English

Perl,将正则表达式匹配赋予标量

[英]Perl, Assign regex match to scalar

There's an example snippet in Mail::POP3Client in which theres a piece of syntax that I don't understand why or how it's working: Mail :: POP3Client中有一个示例代码段,其中有一段语法我不明白为什么或如何工作:

foreach ( $pop->Head( $i ) ) {
    /^(From|Subject):\s+/i and print $_, "\n";
}

The regex bit in particular. 特别是正则表达式。 $_ remains the same after that line but only the match is printed. $_在该行之后保持不变,但仅打印匹配。 An additional question; 另一个问题; How could I assign the match of that regex to a scalar of my own so I can use that instead of just print it? 我如何将该正则表达式的匹配分配给我自己的标量,以便我可以使用它而不是仅仅打印它?

This is actually pretty tricky. 这实际上非常棘手。 What it's doing is making use of perl's short circuiting feature to make a conditional statement. 它正在做的是利用perl的短路功能来制作条件语句。 it is the same as saying this. 这跟说这个是一样的。

if (/^(From|Subject):\s+/i) { 
    print $_;
}

It works because perl stops evaluating and statements after something evaluates to 0. and unless otherwise specified a regex in the form /regex/ instead of $somevar =~ /regex/ will apply the regex to the default variable, $_ 它的工作原理是因为perl在评估为0之后停止计算和语句。除非另有说明,否则形式为/regex/而不是$somevar =~ /regex/的正则$somevar =~ /regex/将正则表达式应用于默认变量$_

you can store it like this 你可以这样存储它

my $var;    
if (/^(From|Subject):\s+/i) { 
        $var = $_;
}

or you could use a capture group 或者您可以使用捕获组

/^((?:From|Subject):\s+)/i

which will store the whole thing into $1 这将整个东西存入$1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM