Search code examples
c++perlpopen

Error executing a perl command using popen in C++


In my c++ program I want to execute a perl comand and read the output returned by the execution. I use popen for that, but I get an error when executing my command:

Command:

string cmd = "perl -ne 's/^\\S+\\s//; if ((/" +
            pattern1+ " START/ .. /" + pattern2+ " END/) && /find/)"
            " { print \"$_\"}' file";
stream = popen(cmd.c_str(),"r");

If I execute this command in the command line it works, but in C++ i get this error:

Search pattern not terminated at -e line 1.

The command that works in command line is, in C++ I already escaped the '\' and '"':

perl -ne 's/^\\S+\\s//; if ((/aaa START/ .. /bbb END/) && /find/) { print "$_"}' file

If I execute this command, it works: "perl -ne print $_ file". But my initial command doesn't. What I am doing wrong. Thanks.


Solution

  • It's your escape characters \. You'll have to double them up in the C++ string as \\ gets turned into \. Then the shell does it's processing as you see on the command line. i.e. another round of \\ turned into \.