How to read STDOUT from a subprocess in OO Perl

In Perl, one way to read the STDOUT subprocess is to use open:

open(PIPE, "ls -l |");

I was looking for a more object oriented way to do this, and I used it successfully IO::Pipe. However, I want to detect errors, especially if the command is not executable. However, I cannot figure out how to do this using IO::Pipe. Here is what I have:

use strict;
use warnings;

use IO::Pipe;


my($cmd) = join (" ", @ARGV);

open(PIPE, "$cmd |") || die qq(error opening PIPE);
while (<PIPE>) {
        chomp;
        print "DBG1: $_\n";
}

close PIPE;

my($pipe) = IO::Pipe->new();
$pipe->reader($cmd);
die qq(error opening IO::Pipe) if $pipe->eof();

while (<$pipe>) {
        chomp;
        print "DBG2: $_\n";
}

$pipe->close();

If the subprocess command is incorrect, both checks will be correct die. If the subprocess does not exit, it eof()will report an error, even if the command itself is in order:

$ perl pipe.pl "ls -l >/dev/null"
error opening IO::Pipe at pipe.pl line 20.

A bunch of questions, then:

OO Perl? IO::Pipe ? , , ? , ? , , IPC::Open2 IPC::Open3. , .

+4
2

IO:: Pipe. , eof . , , , . eof PIPE. , .

, , , IO:: Pipe .

# IO::Pipe: Cannot exec: No such file or directory
$pipe->reader("hajlalglagl");
+3

Backticks , , , , .

use strict;
use warnings;
use Backticks;
my $cmd = Backticks->new(join (" ", @ARGV));
$cmd->run();

if ($cmd->success){
        print $cmd->stdout
} else {
        print "Command failed\n";
}

,

io_pipe.pl "uname -o"

GNU/Linux

io_pipe.pl "uname -z"

Command failed

@thisSuitIsNotBlack, perl. "" POD. , :

backticks :: Simple. ... Perl OO, , :

 use Backticks;
 no Backticks;
0

Source: https://habr.com/ru/post/1615304/


All Articles