Reputation: 60084
Perl docs recommend this:
$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.
However, I do not want to modify $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?
Upvotes: 8
Views: 4642
Reputation: 183612
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:
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. That flag was added quite recently, in 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.
Upvotes: 2
Reputation: 168
For completeness.
If you are stuck with an older version of perl
.
And really want to use the s///
command without resorting to using a temporary variable.
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.
Instead of what s///
does - of returning the count of substitutions.
Upvotes: -1
Reputation: 9697
As ruakh wrote, /r
is new in perl 5.14. However you can do this in previous versions of perl:
(my $foo = $bar) =~ s/this/that/;
Upvotes: 20