1

I am trying to replace string with a new string containing $(dollar) sign in a existing file.

I have used below (regex) line in my code but I am not able get the expected result. Please suggest the solution.

system("perl -pi -e \"s/length\\s+.*/length [index $pkt_len]/g if /^\\s*set_value\\s+length/\" $filename")
5
  • 1
    Could you please mention the input string? Commented May 25, 2020 at 8:09
  • set_value length 1 . Instead of $ symbol its value is printed Commented May 25, 2020 at 8:36
  • Instead of calling a new perl process from within a perl process, you could also do everything in the first perl. Please show the content of the file $filename, the value of $pkt_len and what should be the expected output (the new content of $filename) Commented May 25, 2020 at 13:50
  • 1
    Not that you should do this, but it you want to call perl from within a Perl program, you should use $^X. That's the current perl binary that's running. If plain perl finds another one in your path but uses your current environment, you can get mismatches in library versions. Commented May 25, 2020 at 16:11
  • in the $filename i want to replace "set_value length 1" string with "set_value length [index $pkt_len]". i am able to replace but instead of $ symbol it's value is appearing in the file. Commented May 26, 2020 at 5:32

2 Answers 2

1

The way to find the solution is during debug you should print out the line of the system call and test it "by hand" if it works as expected in the shell.

My guess is that

system("perl -pi -e 's/length\\s+.*/length [index \\\$pkt_len]/g if /^\\s*set_value\\s+length/' $filename")

is a solution.

Sign up to request clarification or add additional context in comments.

Comments

1

You need 7 backslashes (!):

system("echo a | perl -pe \"s/a/\\\\\\\$foo/\"");

Output:

$foo
  • First "echo a | perl -pe \"s/a/\\\\\\\$foo/\"" is interpreted by perl which reduces the string to echo a | perl -pe "s/a/\\\$foo/"
  • Then it is parsed by the shell sh to give : echo a | perl -pe s/a/\$foo/
  • Finally, it is parsed by perl a second time to give the output $foo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.