Hi Peter,
Thanks for your reply.
On 2 Mar 2012 02:48:28 -0000
Peter Scott <[email protected]> wrote:
>
> It doesn't have flaws. You could do it without the module with a
> piped open:
>
> sub run_cmd
> {
> my $cmd = shift;
>
> open my $fh, '-|', "$cmd 2>&1" or die "open: $!";
> print while <$fh>;
> close $fh;
> return $? >> 8;
> }
>
Thanks for your reply. I previously tried open as well but I was unable
to get a return code back. Your solution gives the return code back.
The only thing I have to do is to check if the executable will be found
in the PATH.
I tried out all 3 solutions like this:
<--------------------------------snip------------------------>
#! /usr/bin/perl
use strict;
use warnings;
use 5.010;
use IPC::Open3;
use File::Which;
# one good cmd, one with an invalid parameter, and one not to be found
my @cmds = ( "uname -a", "uname -aarst", "unamre -a");
foreach ( @cmds ) { say run_cmd1($_); };
foreach ( @cmds ) { say run_cmd2($_); };
foreach ( @cmds ) { say run_cmd3($_); };
exit;
sub run_cmd1 {
my $cmd = shift @_;
print "Issuing [$cmd]\n";
my $pid = open3(undef, *CMD_OUT, *CMD_OUT,$cmd);
print while <CMD_OUT>;
waitpid($pid,0);
return $? >>8;
}
sub run_cmd2 {
my $cmd = shift;
print "Issuing [$cmd]\n";
return 1 if ( not is_executable($cmd));
open my $fh, '-|', "$cmd 2>&1" or die "open: $!";
print while <$fh>;
close $fh;
return $? >> 8;
}
sub run_cmd3 {
my $cmd = shift @_;
print "Issuing [$cmd]\n";
return 1 if ( not is_executable($cmd));
open(CMD,"$cmd 2>&1|") or die "Can't run $cmd $cmd!";
print while <CMD>;
return $? >> 8;
}
sub is_executable {
my $cmd = shift @_;
my ($cname,undef) = split /\s+/, $cmd;
$cname = which($cname);
if ( not defined $cname ) {
say "$cmd not found or not executable.";
return 0;
}
return 1;
}
<--------------------------------snap------------------------>
But I get those errors which confuse me.
Use of uninitialized value $cmd in concatenation (.) or string
at ./testcmd2.pl line 34, <CMD_OUT> line 4.
Issuing []
and more of these.
What is going on here? I assume that I made a typical beginner's
mistake but do not see where.
Another question I have: Where do I find what '-|' means? I mean the
minus before the pipe char.
--
Manfred
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/