|more useful options|
Modules which improve system() ?by pjf (Curate)
|on Jun 23, 2006 at 07:51 UTC||Need Help??|
pjf has asked for the
wisdom of the Perl Monks concerning the following question:
Ahoy there monks,
I'm writing some material which is primarily aimed at system administrators who'd like to use Perl to make their life easier. Part of that discussion involves demonstrating how to use system() to call external programs, but unfortunately I've hit a snag.
Checking system() to see if anything has gone wrong is a pain. Our command may not actually get run, in which case $? == -1, or it may have been killed by a signal, in which case WIFSIGNALED($?) will be true. It may have run to completion, but the exit code may not have been something that we expect.
Handling the error status from system is always a pain, even in the most simpliest case:
system("some_command") and die "...";
Some less experienced programmers may see the and die and think it is a mistake, since for all other Perl built-ins one would use or die. Even the experienced programmers would be hard-pressed to say what should actually go in the die message. Surely $! should be reported if $? == -1, but otherwise one ends up with an awkward series of statements to unpack signals and exit status. And what if our requirements change later on, and it's okay if some_command also returns an exit status of 1? Surely there must be a better way?
Unfortunately, I can't seem to find a Perl module that makes this easy. I'd like to be able to write code that reads:
use Some::Module qw(run);
and have run throw an appropriately verbose exception if the command doesn't start, gets zapped by a signal, or returns non-zero. If I later need to allow my command to return a couple of different status values (say 0, 1 and 5), then I can change my code to be:
my $exit_value = run( [0,1,5], "some_command");
and be certain that $exit_value will be either 0, 1 or 5, or an exception will be thrown.
Have I been missing this obviously simple module all this time, and if so, what is it called? (If not, then watch this space for a new module announcement.)
Update: You can find my solution to the problem using IPC::System::Simple.
Perl Training Australia