perlquestion
keithw99
<p>I'm trying to use Perl in a command-line fashion where I'm getting a list from a STDIN pipe and using those values to perform a regex substitution on a file. In a script, I know that I can create a different file handle for each input source, but how would I do it at the command line?</p>
<p>In the example below, suppose I have an executable command "print_list" that prints a list of words to STDOUT (separated by newlines), and I want Perl to search through a file called file.txt and replace all instances of these words (from the piped list) with the string "foo". The following command does *NOT* work, but I wanted to at least illustrate what I'm trying to do:</p>
<code>
./print_list | perl -i -ne 's/\Q$_\E/foo/g' file.txt
</code>
<p>The problem here is that I'm confusing Perl with input sources. There's a STDIN pipe coming from the left, and there's a file argument coming from the right. I would like the '$_' variable to come from the pipe, but when I add the 'file.txt' argument, the '$_' variable gets its value from the file instead. I'm also curious how to control which source the '<>' variable represents.</p>
<p>Is there any way this is even possible?</p>
<p>(if you're wondering about the \Q..\E in the regex, it's because the words may contain many special characters that would be misinterpreted as regex operators, so I need to escape them)</p>