0

I have a file containing search and replace string in a single line.

And I am reading that file, using split to separate search and replace string and apply it on a variable.


File:

(.*) pre_$1

Perl Code:

$str = "a";

$line = < FILEHANDLE>; # Read above file.Contains (.*) pre_$1

my ($ss,$rs) = split /\s/,$line;

$str =~ s/$ss/$rs/ee;

This seems to be not working.

I tried to look online, one result is close which is wrap the replace string in both single and double quotes.

i.e.:

$rs = '"pre_$1"';

This works if its in the script, but if I read from file I done see any replacement.

Can someone point me to what I am doing wrong here?

Thanks.

Zendie
  • 1,176
  • 1
  • 13
  • 30
Arthes
  • 79
  • 1
  • 8
  • Hi, Please note the answer post suggested has both the search and replace string in the script. But I am reading them from a file (as noted in my question). I have tried the solution and it didn't work (also noted in my question) – Arthes Sep 27 '19 at 08:11

1 Answers1

3

s//$rs/ee expects $rs to contains valid Perl code. pre_$1 is not valid Perl code. It's a very bad idea to expect the user to provide Perl code anyway.

Solution:

use String::Substitution qw( gsub_modify );

gsub_modify($str, $ss, $rs);
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Thanks for the reply. The end user here are Perl aware. Also the problem is I need to use inbuild functions here. I have found a workaround, but it's very crude. ` my $line = <$fh>; my ($ss,$rs) = split /\s/,$line; if ($str =~ m/$ss/){ my $match = $1; $rs =~ s/(\$\w+)/$match/eeg; $str = $rs; } ` – Arthes Sep 27 '19 at 04:15
  • Re "*I need to use inbuild functions here.*", If you can use the code we post on SO, you can use the code we post on CPAN. – ikegami Sep 27 '19 at 06:12
  • 1
    Re "*`s/(\$\w+)/$match/eeg`*", That should be `s/(\$\w+)/$match/g` – ikegami Sep 27 '19 at 06:18
  • I work on remote machine where I cannot access internet and ftp isn't allowed. So I cannot install String::Substitution (PERL v5.16.3). I changed the eeg to g. Thanks – Arthes Sep 27 '19 at 08:18
  • That's not true. You can get your own script on it, so you can get the module on it too! – ikegami Sep 27 '19 at 08:38
  • I appreciate the answer but please stop speculating on my work env without info. Obviously I am duplicating a piece of code to show the issue here. – Arthes Sep 27 '19 at 11:28
  • I didn't do any speculating; you indicated that you able to change code on the machine. If you can do that, you can install String::Substitution. There is no difference between a script and a module. – ikegami Sep 27 '19 at 12:00