perl s/this/that/r ==> "Bareword found where operator expected"
Asked Answered
R

3

8

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?

Racquelracquet answered 20/12, 2011 at 19:44 Comment(5)
Is this running on Perl 5.14… ? (Make sure you have a require v5.14; in your header…)Sauls
Edit: apparently use v5.13.2 is the minimum level for s///r.Sauls
What have we learned here? We have learned that we should read the docs that came with out perl distribution rather than reading docs from "somewhere on the web". :-)Oubre
@BRPocock, 5.13.x are a dev releases. No reason to mention those.Dispensation
@tadmc, I thought the lesson was: Upgrading to the latest Perl has benefits :)Dispensation
K
20

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/;
Kazmirci answered 20/12, 2011 at 19:53 Comment(0)
L
2

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.

Lorola answered 20/12, 2011 at 19:49 Comment(0)
V
-1

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.

Vaporous answered 21/1, 2021 at 3:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.