如何在不设置变量的情况下执行 perl 内联正则表达式? [英] How to do perl inline regex without setting to a variable?
问题描述
通常,如果您想使用正则表达式更改变量,请执行以下操作:
Normally if you wish to change a variable with regex you do this:
$string =~ s/matchCase/changeCase/;
但是有没有一种方法可以简单地进行内联替换而不将其设置回变量?
But is there a way to simply do the replace inline without setting it back to the variable?
我希望在这样的地方使用它:
I wish to use it in something like this:
my $name="jason";
print "Your name without spaces is: " $name => (/\s+/''/g);
类似的东西,有点像 PHP 中的 preg_replace 函数.
Something like that, kind of like the preg_replace function in PHP.
推荐答案
针对 Perl 5.14 进行了修订.
Revised for Perl 5.14.
自 5.14 起,使用 /r
标志来返回替换,您可以这样做:
Since 5.14, with the /r
flag to return the substitution, you can do this:
print "Your name without spaces is: [", do { $name =~ s/\s+//gr; }
, "]\n";
<小时>
您可以使用 map
和一个词法变量.
my $name=" jason ";
print "Your name without spaces is: ["
, ( map { my $a = $_; $a =~ s/\s+//g; $a } ( $name ))
, "]\n";
现在,您必须使用词法,因为 $_ 会别名,从而修改您的变量.
Now, you have to use a lexical because $_ will alias and thus modify your variable.
输出是
Your name without spaces is: [jason]
# but: $name still ' jason '
诚然do
也能正常工作(也许更好)
Admittedly do
will work just as well (and perhaps better)
print "Your name without spaces is: ["
, do { my ( $a = $name ) =~ s/\s+//g; $a }
, "]\n";
但是词法复制仍然存在.my
中的赋值是一些人(不是我)喜欢的缩写.
But the lexical copying is still there. The assignment within in the my
is an abbreviation that some people prefer (not me).
对于这个习语,我开发了一个我称之为 filter
的操作符:
For this idiom, I have developed an operator I call filter
:
sub filter (&@) {
my $block = shift;
if ( wantarray ) {
return map { &$block; $_ } @_ ? @_ : $_;
}
else {
local $_ = shift || $_;
$block->( $_ );
return $_;
}
}
你这样称呼它:
print "Your name without spaces is: [", ( filter { s/\s+//g } $name )
, "]\n";
这篇关于如何在不设置变量的情况下执行 perl 内联正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!