in reply to Opening not-existing command - Error Handling

So my question is, how can I check when I open a process, if the command really exists?
Just try to run the command and see if that fails. Don't fail fatally (die()) if you do not want to.

use strict; use warnings; my $run_cmd = "dira"; if ( open(my $CMD, "$run_cmd |") ) { while( <$CMD> ) { print "$_"; } close($CMD); } else { die "Problem executing command $run_cmd - $!"; # ... or something non-fatal }
Alternatively, you could wrap your stuff into an eval { ... } block and then examine $@ (e.g. Problem executing command in the example above). You could also try one of the many CPAN modules that supports handling of exceptions.

Update:

Another possibility would be to loop through all pathes in the environment variable PATH and then checking if the command exists.
There is this ancient thread and some CPAN modules like Dir::Which or File::Which that can be used to perform apriori checks - but see cdarke's comments below.

Update2:
The program above was tested and worked fine under Linux. Since I am not a Windows-expert, I can only do wild guesses on what the problem could be:

Replies are listed 'Best First'.
Re^2: Opening not-existing command - Error Handling
by Dirk80 (Pilgrim) on Aug 16, 2011 at 12:10 UTC

    Thanks. Problem is that even if I take the not-existing command "dira" I'm not going into the else block. I verified it with the debugger.

    Do you enter the else block on your machine if you choose a not-existing command?

      On GNU/Linux (line 12 is test in "if"; second message was generated in "else" body) & perl 5.8.8 ...

      Can't exec "dira": No such file or directory at p.pl line 12. Problem executing command dira - No such file or directory at p.pl lin +e 18.
      ...