[英]perl s/this/that/r ==> “Bareword found where operator expected”
Perl docs recommend this: Perl 文档推荐这个:
$foo = $bar =~ s/this/that/r;
However, I get this error:但是,我收到此错误:
Bareword found where operator expected near
"s/this/that/r" (#1)
This is specific to the r
modifier, without it the code works.这是特定于
r
修饰符的,没有它代码就可以工作。 However, I do not want to modify $bar
.但是,我不想修改
$bar
。 I can, of course, replace我当然可以替换
my $foo = $bar =~ s/this/that/r;
with和
my $foo = $bar;
$foo =~ s/this/that/;
Is there a better solution?有更好的解决方案吗?
As ruakh wrote, /r
is new in perl 5.14.正如 ruakh 所写,
/r
是 perl 5.14 中的新内容。 However you can do this in previous versions of perl:但是,您可以在以前版本的 perl 中执行此操作:
(my $foo = $bar) =~ s/this/that/;
There's no better solution, no (though I usually write it on one line, since the s///
is essentially serving as part of the initialization process:没有更好的解决方案,不(虽然我通常将它写在一行上,因为
s///
本质上是作为初始化过程的一部分:
my $foo = $bar; $foo =~ s/this/that/;
By the way, the reason for your error-message is almost certainly that you're running a version of Perl that doesn't support the /r
flag.顺便说一句,您的错误消息的原因几乎可以肯定是您运行的 Perl 版本不支持
/r
标志。 That flag was added quite recently, in Perl 5.14.该标志是最近在 Perl 5.14 中添加的。 You might find it easier to develop using the documentation for your own version;
您可能会发现使用您自己版本的文档进行开发更容易; for example, http://perldoc.perl.org/5.12.4/perlop.html if you're on Perl 5.12.4.
例如,如果您使用的是 Perl 5.12.4,则为http://perldoc.perl.org/5.12.4/perlop.html 。
For completeness.为了完整性。 If you are stuck with an older version of
perl
.如果您坚持使用旧版本的
perl
。 And really want to use the s///
command without resorting to using a temporary variable.并且真的想使用
s///
命令而不诉诸使用临时变量。 Here is one way:这是一种方法:
perl -E 'say map { s/_iter\d+\s*$//; $_ } $ENV{PWD}'
Basically use map to transform a copy of the string and return the final output.基本上使用 map 来转换字符串的副本并返回最终输出。 Instead of what
s///
does - of returning the count of substitutions.而不是
s///
所做的 - 返回替换计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.