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

O monks, hear my plea for enlightenment:

Is there a graceful way to test whether a particular external program is available? I could do a system("which foo"), but that wouldn't be portable. I could attempt to execute foo and test for an error, but I don't actually want to execute foo yet, I just want to do an initial test to see whether there's any problem with the user's configuration. I could split $ENV{PATH} and look in every directory it contains, but that would be a lot of work.

On a related note, why does use of $ENV{PATH} with the -T pragma cause an error/warning, and is there a good workaround? I'm modifying someone else's CGI script to try to make it do better error checking.

Thanks in advance, O monks!

Thanks, all, for the suggestions!! I'm going to go with Aristotle's method, because it's someone else's project, and they might not want me to submit a patch that adds dependencies.

  • Comment on checking external program for availability?

Replies are listed 'Best First'.
Re: checking external program for availability?
by Aristotle (Chancellor) on Dec 21, 2004 at 20:10 UTC

    I could split $ENV{PATH} and look in every directory it contains, but that would be a lot of work.

    Would it?

    use File::Spec::Functions qw( catfile path ); my $foo_available = grep -x catfile( $_, 'foo' ), path;

    (Note grep in scalar context — it returns the number of matches.)

    Makeshifts last the longest.

Re: checking external program for availability?
by Ovid (Cardinal) on Dec 21, 2004 at 20:38 UTC

    Check the App::Info namespace to see one way to check to see if programs are installed. I'm sure that the author wouldn't mind new programs being handled by it.

    And the use of $ENV{PATH} will cause an error with taint checking because Perl marks "unsafe" data as tainted when in taint mode. "unsafe" data is essentially any data that was not explicitly set (or untainted) by the Perl executable. Since Perl doesn't know who set the environment variables, it has no way of knowing that some malicious hacker hasn't added /usr/bin/malicious/ to your path. See perlsec for more information.

    Cheers,
    Ovid

    New address of my CGI Course.

Re: checking external program for availability?
by phenom (Chaplain) on Dec 21, 2004 at 20:17 UTC
Re: checking external program for availability?
by elwarren (Priest) on Dec 22, 2004 at 00:24 UTC
    Incase you didn't notice in the first post using grep, the -x function tests whether a file is executable. Like so:
    if ( -x '/path/to/file' ) { # file is executable, run it system('/path/to/file'); } else { # whatever system('/run/something/else'); }
Re: checking external program for availability?
by samgold (Scribe) on Dec 22, 2004 at 15:56 UTC
    Take a look at File::Find. I think that may be what you are looking for.