Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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?

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:

./print_list | perl -i -ne 's/\Q$_\E/foo/g' file.txt

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.

Is there any way this is even possible?

(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)


In reply to How to handle both a STDIN pipe and file from command line? by keithw99

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-24 00:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found