【问题标题】:How to do perl inline regex without setting to a variable?如何在不设置变量的情况下执行 perl 内联正则表达式?
【发布时间】:2011-03-20 06:45:48
【问题描述】:

通常,如果您希望使用正则表达式更改变量,请执行以下操作:

$string =~ s/matchCase/changeCase/; 

但是有没有办法简单地进行内联替换而不将其设置回变量?

我希望在这样的情况下使用它:

my $name="jason";
print "Your name without spaces is: " $name => (/\s+/''/g);

类似的东西,有点像 PHP 中的 preg_replace 函数。

【问题讨论】:

标签: regex perl replace


【解决方案1】:

针对 Perl 5.14 进行了修订。

自 5.14 起,使用 /r 标志来返回替换,您可以这样做:

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";

现在,您必须使用词法,因为 $_ 将 别名 从而修改您的变量。

输出是

Your name without spaces is: [jason]
# but: $name still ' jason '

诚然,do 也可以正常工作(也许更好)

print "Your name without spaces is: ["
    , do { my ( $a = $name ) =~ s/\s+//g; $a }
    , "]\n";

但是词法复制仍然存在。 my 中的赋值是一些人(不是我)喜欢的缩写。

对于这个成语,我开发了一个运算符,我称之为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";

【讨论】:

  • 或者你可以使用词法变量而不使用map: print "Your name without spaces is: [", do{my $a=$name; $a=~s/\s+//g; $a}, "]\n"
  • @mobrule:我是在你输入的时候添加的。 :D
  • 接受了这个,因为它有更多的解释。
【解决方案2】:
print "Your name without spaces is: @{[map { s/\s+//g; $_ } $name]}\n";

【讨论】:

    猜你喜欢
    • 2018-10-21
    • 2014-07-30
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多