title: Perl: process string with shell command (pipe)
body: <p>Assume a pipeline with three programs:</p>
  
  <p><code>start | middle | end</code></p>
  
  <p>If <code>start</code> and <code>end</code> are now part of one perl script, how can I pipe data through a shell command in the perl script, in order to pass through <code>middle</code>?</p>
  
  <p>I tried the following (apologies for lack of strict mode, it was supposed to be a simple proof of concept):</p>
  
  <pre><code>#!/usr/bin/perl -n
  
  # Output of "start" stage
  $start = "a b c d\n";
  
  # This shell command is "middle"
  open (PR, "| sed -E 's/a/-/g' |") or die 'Failed to start sed';
  
  # Pipe data from "start" into "middle"
  print PR $start;
  
  # Read data from "middle" into "end"
  $end = "";
  while (&lt;PR&gt;) {
      $end .= $_;
  }
  
  close PR;
  
  # Apply "end" and print output
  $end =~ s/b/+/g;
  
  print $end;
  </code></pre>
  
  <p>Expected output:</p>
  
  <p><code>- + c d</code></p>
  
  <p>Actual output:</p>
  
  <p>none, until I hit ENTER, then I get <code>- b c d</code>.  The <code>middle</code> command is receiving data from <code>start</code> and processing it, but the output is going to STDOUT instead of <code>end</code>.  Also, the attempt to read from <code>middle</code> seems to be reading from STDIN instead (hence the relevance of hitting ENTER).</p>
  
  <p>I'm aware that this could all easily be done in one line of perl (or sed); my problem is how to do piping in perl, not how to replace chars in a string.</p>