title: Call system command from perl script printing the output AND storing it into a variable
body: <p>I want to send a command, for example, execute a ping:</p>
  
  <pre><code>ping google.es -n 500
  </code></pre>
  
  <p>I can execute the command with:</p>
  
  <pre><code>my $command =  "ping google.es -n 500";
  system($command);
  </code></pre>
  
  <p>And I will get the output printed while it runs.</p>
  
  <p>I can store it into a variable with:</p>
  
  <pre><code>my $command =  "ping google.es -n 500";
  my $output = `$command`;
  </code></pre>
  
  <p>But how can I get the output of the command <strong>WHILE</strong> it is running and then use the output in a variable?</p>
  
  <p>I´ve see a solution like this, but it does not work. It runs the script and <strong>when it has finished</strong> it will print the result:</p>
  
  <pre><code>my $variable = '';
  open my $command_pipe, "-|", $command or die "Pipe from $command failed: $!";
  while (&lt;$command_pipe&gt;) {
      print  $_;
      $variable . = $_;
  }
  </code></pre>
  
  <p><strong>UPDATE</strong>: 
  Example to show the problem. I have 2 perl scripts and one calls the other:</p>
  
  <p>test.pl:</p>
  
  <pre><code>use strict;
  use warnings;
  
  my $command = 'perl test2.pl';
  
  print "Localtime: " . localtime() . "\n";
  
  my $variable = '';
  open my $command_pipe, "-|", $command or die "Pipe from $command failed: $!";
  while (&lt;$command_pipe&gt;) {
      print "[" .  localtime() . "] " . $_;
      $variable .= $_;
  }
  
  print "Localtime: " . localtime() . "\n";
  print "Loop finished:\n$variable\n";
  </code></pre>
  
  <p>Second file test2.pl:</p>
  
  <pre><code>use strict;
  use warnings;
  
  
  print "Waiting 10 sec\n";
  my $i = 0;
  while($i &lt; 10){
      sleep(1);
      print "$i\n";
      $i++;
  }
  print "That's it!\n";
  </code></pre>
  
  <p>And the output is:</p>
  
  <pre><code>C:\Users\****\Desktop\****&gt;perl test.pl
  Localtime: Wed Oct 17 13:47:06 2018
  [Wed Oct 17 13:47:16 2018] Waiting 10 sec
  [Wed Oct 17 13:47:16 2018] 0
  [Wed Oct 17 13:47:16 2018] 1
  [Wed Oct 17 13:47:16 2018] 2
  [Wed Oct 17 13:47:16 2018] 3
  [Wed Oct 17 13:47:16 2018] 4
  [Wed Oct 17 13:47:16 2018] 5
  [Wed Oct 17 13:47:16 2018] 6
  [Wed Oct 17 13:47:16 2018] 7
  [Wed Oct 17 13:47:16 2018] 8
  [Wed Oct 17 13:47:16 2018] 9
  [Wed Oct 17 13:47:16 2018] That's it!
  Localtime: Wed Oct 17 13:47:16 2018
  Loop finished:
  Waiting 10 sec
  0
  1
  2
  3
  4
  5
  6
  7
  8
  9
  That's it!
  </code></pre>
  
  <p>As you can see everything is just printed after the 10 seconds of the second script.</p>