Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

bareword

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?

like image 545
sds Avatar asked Dec 20 '11 19:12

sds


2 Answers

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/;
like image 88
bvr Avatar answered Oct 30 '22 06:10

bvr


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.

like image 23
ruakh Avatar answered Oct 30 '22 06:10

ruakh