chandu76 has asked for the wisdom of the Perl Monks concerning the following question:

how can exit based on exit code?
open(FILE,"run_tool -f "test.tcl" 2>&1|"); open(LOG,">log"); while(<TEMP>){ print; print log; }
if test.tcl file not exists then tool is invoked and it is hanged.how can I come out of while loop. or another case is if did not use exit in tcl script the same problem tool runs and hangs. how can I exit in such situations? I can't use " exit 1 if ($_ =~ /^(Error :)); " becuase tool should run though it gets error messages,but should exit depending on exit status.

Replies are listed 'Best First'.
Re: stop process based on exit status.
by jdalbec (Deacon) on Aug 14, 2004 at 13:27 UTC
    You have a bareword test.tcl in your code. Also, you open FILE but you then read from TEMP. You should always
    use strict; use warnings;
    I don't think you can get an exit status from a pipe. If you're on *n*x you could try
    open(FILE,'run_tool -f "test.tcl" 2>&1; echo Status code: $?|');
    and
    exit 1 if ($_ =~ /^Status code: [^0]/)
    I'm not sure how to do the equivalent in Windows.

    Another option is to use -f (see man perlfunc) to test whether the file exists before you run the command.

Re: stop process based on exit status.
by Mr_Person (Hermit) on Aug 14, 2004 at 16:22 UTC
    This may be a little overblown for what you need, but it will capture both the STDOUT and the STDERR to a log file, die if the program does not exist, and display the return code.
    #!/usr/bin/perl use strict; use warnings; use IPC::Run qw( start pump finish ); open(LOG, '>', 'log') or die "Unable to open log: $!"; my ($in, $out); my $h = start([ 'run_tool', '-f', 'test.tcl' ], \$in, \$out, \$out); while($h->pump) { print LOG $out; $out = ''; } $h->finish; close(LOG); print "Exit code was: " . $h->result . "\n";
    You'll probably want to take a closer look at the IPC::Run docs for more details on what all it can do. It also offers fairly flexible control over interactive programs if you want to do that in the future. I tend to use it over open or system any time I need to start doing anything more than just run the program.