0

I am trying to execute a shell command, and capture its output within perl using backticks, and send the output to STDOUT at the same time,

#!/usr/bin/perl

use strict;
use warnings;

my $output = `echo test1 | tee /dev/fd/1`;

print "op : $output";

This works and gives me the output like this,

op : test1
test1

However, when I'm assigning the output of the command to an array instead of a scalar, it does not work as before,

my @output = `echo test1 | tee /dev/fd/1`;

print "op : $output[0]";

This prints the array variable, but not the echo output,

op : test1

Meaning that the shell command output is not being sent to STDOUT. Can someone explain why this is happening?

Any help much appreciated.

Jenson Jose
  • 532
  • 2
  • 15
  • 33
  • 2
    Your first version isn't doing what you think it's doing. STDOUT is redirected to the pipe that goes to perl, so you're just writing each line of output twice to STDOUT, and both of them are ending up in the perl variable. In the second version, the second copy is in `$output[1]`. – Barmar Aug 22 '13 at 08:05
  • Many thanks for pointing that out - what would be the correct way to do it? – Jenson Jose Aug 22 '13 at 08:55
  • Not really, I had a look at that question before posting. My question is different from that in the sense that I was not really asking about *how* to do it. – Jenson Jose Aug 22 '13 at 11:43
  • You wrote "what would be the correct way to do it?" Isn't that asking _how_ to do it? – Barmar Aug 22 '13 at 11:45
  • Well, agreed, but it wasn't part of the original question, thats all I was trying to say, but anyways. – Jenson Jose Aug 22 '13 at 11:50
  • It seemed to be implied, since you started the question by saying it's what you're trying to do. I explained in the comment why your code doesn't work, and the linked question provides the solution. – Barmar Aug 22 '13 at 11:58

1 Answers1

0

You can refer to this FAQ link to know how to save stdout/stderr from an external command.

You can refer to this answer for knowing how to redirect output of shell command to perl variable and stdout. Related question:

Community
  • 1
  • 1
Unos
  • 1,293
  • 2
  • 14
  • 35