Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute an external script while capturing both output and exit code in Perl?

I'm trying to check for an SVN tag existence from a Perl script. So I try calling svn info $url, read exit code and suppress standard output and standard error streams. However, I struggle to do this elegantly (there are probably better ways to ask SVN about a tag, but that's not the point here):

my $output = `svn info $url/tags/$tag`;

This suppresses the output while putting it into $output. Exit code is lost.

my $output = `svn info $url/tags/$tag 2>&1`;

This suppresses both STDERR and STDOUT and puts them both into $output. Exit code is again lost.

my $exitcode = system("svn", "info", "$url/tags/$tag");

This catches the exit code, but the actual output and error stream is visible to the user.

open( STDERR, q{>}, "/dev/null" );
open my $fh, q{>}, "/dev/null";
select($fh);
if (system("svn", "info", "$url/tags/$tag") != 0) {
   select(STDOUT);
   print ("Tag doesn't exist!");
   do_something_with_exit();
}
select(STDOUT);
print "Exit code: $exitcode";

This kills the STDOUT and STDERR and catches the exit code, but it's ugly because I'd have to remeber to switch the STDOUT back to original.

So, is there any more elegant solution?

like image 522
Nikolai Prokoschenko Avatar asked Feb 05 '10 09:02

Nikolai Prokoschenko


Video Answer


3 Answers

Try using $?.e.g.

my $output = `svn info $url/tags/$tag`;
my $extcode = $?>>8;
like image 100
bhups Avatar answered Oct 19 '22 14:10

bhups


What happens when you try it with IPC::System::Simple? That module handles most of the details of these sorts of problems:

 use IPC::System::Simple qw(capturex $EXITVAL);

 my $output = capturex( "some_command", @args );
 my $exit   = $EXITVAL;
like image 31
brian d foy Avatar answered Oct 19 '22 13:10

brian d foy


 my $output = `svn info $url/tags/$tag 2>&1`;

This suppresses both STDERR and STDOUT and puts them both into $output. Exit code is again lost

Are you sure the exit code is lost? When I try this, I get the exit code in $?.

like image 1
Hans W Avatar answered Oct 19 '22 14:10

Hans W