http://www.perlmonks.org?node_id=1004659

dr.jekyllandme has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I have a program that issues some system calls. I would like to do 2 things in my function - The system call's output should be stored in a variable and also output to STDOUT. I guess I am asking for a way to combine both system and qx( backtick ). Is this even possible? Here is a snapshot of my code:
#!usr/bin/perl use strict; use warnings; my $cmd = qx("ls -l"); print "$cmd";
Thank you.
  • Comment on How to output backtick or qx to a variable and STDOUT at the same time?
  • Download Code

Replies are listed 'Best First'.
Re: How to output backtick or qx to a variable and STDOUT at the same time?
by Athanasius (Archbishop) on Nov 20, 2012 at 06:03 UTC

    I’m not exactly clear on what you want, but the CPAN module Capture::Tiny will almost certainly meet your needs. For example (from the documentation):

    ($stdout, $stderr, $exit) = capture { system($cmd, @args); };

    Update: For your specific example:

    #!usr/bin/perl use strict; use warnings; use Capture::Tiny qw(capture); my ($stdout, $stderr, $exit) = capture { system('ls', '-l'); }; print "After the system call:\n"; print "\$stdout = $stdout\n"; print "\$stderr = $stderr\n"; print "\$exit = $exit\n";

    Hope that helps,

    Athanasius <°(((><contra mundum

      Thank you! Looking over at Capture::Tiny's doc, I found tee. Which is exactly what I needed. Output both to STDOUT and store in a variable for later use.
      #!usr/bin/perl use strict; use warnings; use Capture::Tiny qw(capture tee); my ($stdout, $stderr, $exit) = tee { system('ls', '-l'); }; print $stdout;
Re: How to output backtick or qx to a variable and STDOUT at the same time?
by Utilitarian (Vicar) on Nov 20, 2012 at 08:39 UTC
    What I suspect your tutor wants you to prove you understand is that assignment returns the value assigned on success.
    Try the following
    perl -e 'print $out=qx(ls );print "+" x 80 , "\n";print $out'
    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."
Re: How to output backtick or qx to a variable and STDOUT at the same time?
by space_monk (Chaplain) on Nov 20, 2012 at 08:36 UTC

    As far as combining system and backtick operation is concerned, it seems to be a little known fact that backticks also set the exit code ($?) value in the same way as system does.

    I'd personally be grateful if someone could show an example of where Capture:Tiny does something that is not done by backticks.

    A Monk aims to give answers to those who have none, and to learn from those who know more.