1

What I am doing seems, to me, as if it should be fairly simple so I am probably going to facepalm after it is answered. With that being said:

I am trying to call an outside (non-PERL) function from within my PERL script. I would like to have the STDOUT from the function both printed to the console (as it occurs) and also I would like to capture that information and return it to the original PERL script that called it.

Attempted solutions include:

#does not return the output
my @output = system($cmd);

#does not display the output as it occurs
my @output = `$cmd`;

#does not display the output as it occurs
eval {$pid = open3($Input, $Output, $Error, $cmd); }; die "open3: $@\n" if $@;

Does anyone know a method that will both print the STDOUT to the screen (in realtime) and also capture the STDOUT and return it to the original source of the call?

  • @aschepler You are correct! That is exactly what I was looking for. Thank you for pointing it out. – Captain Ryan Apr 05 '16 at 22:49
  • Incidentally, how do I close this question or mark it as a duplicate? – Captain Ryan Apr 05 '16 at 22:49
  • You can't do that yet. When you have enough reputation, you can vote to close. It takes five votes to close a question. Users with a gold badge in a tag can duplicate close questions in that tag on their own. You should check the [faq] (reading all of it gives a badge). And https://stackoverflow.com/help/privileges is a nice overview. – simbabque Apr 06 '16 at 08:21

1 Answers1

2

Capture::Tiny can do that. You can either just capture_stdout and print it yourself afterwards, or use tee_stdout to have it print and capture at the same time.

use strict;
use warnings;
use Capture::Tiny 'tee_stdout';

my $stdout = tee_stdout sub { `ls -lah` }; # prints
print "ok\n" if $stdout =~ m/\./;          # matches
simbabque
  • 53,749
  • 8
  • 73
  • 136