How to capture both STDOUT and STDERR in two different variables using Backticks in Perl

后端 未结 4 1133
陌清茗
陌清茗 2021-02-08 17:15

Let\'s say I want to run an external program from my script with backticks and at the same time I want to capture both STDOUT and STDERR but in two different variables. How can

4条回答
  •  一生所求
    2021-02-08 18:06

    You needn't go all the way to open3, which IIRC is only for when you need to read and write to an external command, and even then there are other methods.

    For your problem I suggest using Capture::Tiny, which can capture (or even tee) the STDOUT and STDERR from anything run inside its block. For example, per your question:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use Capture::Tiny qw/capture/;
    
    ...
    
    my ($stdout, $stderr) = capture {
      system ( "snmpwalk -v $version -c $community $hostname $oid" );
    };
    

    For another example consider this functioning code:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use Capture::Tiny qw/capture/;
    
    my ($stdout, $stderr) = capture {
      system ( "echo 'hello'" );
      system ( "date" );
      warn "Arg1!";
    };
    
    print "STDOUT:\n$stdout";
    print "STDERR:\n$stderr";
    

    which just gave me:

    STDOUT:
    hello
    Mon Dec 19 23:59:06 CST 2011
    STDERR:
    Arg1! at ./test.pl line 11.
    

提交回复
热议问题