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

I have code such as that below and it works fine unless the command "my_command" is not found. Then it spits out an error such as:

Can't exec "my_command": No such file or directory

How can I print my own error message instead of the one above if the command is not found? I realize I could turn off warnings, but I don't really want to do that.

#!/usr/bin/perl -w use strict; my $output=`my_command -v`;

Replies are listed 'Best First'.
Re: System command & warnings
by blue_cowdawg (Monsignor) on May 13, 2004 at 14:18 UTC

        How can I print my own error message instead of the one above if the command is not found?

    How about something like this:

    : : : much hand waving.... : my $output=""; eval " $output=`my_command -v`; "; if ($@){ print "it broke!\n"; } else { : whatever... }

    disclaimer: completely untested and I don't know what's in "my_command".

      An eval-block is probably better here than an eval-string.

Re: System command & warnings
by ysth (Canon) on May 13, 2004 at 16:11 UTC
    use warnings; my $output = do { no warnings "exec"; `my_command -v` };
    Caveat: I've had funky stuff happen sometimes combining "no warnings" with -w; haven't gotten around to tracking it down yet, but I'd recommend useing "use warnings" rather than -w.
Re: System command & warnings
by Taulmarill (Deacon) on May 13, 2004 at 14:25 UTC
    i didnīt find a way using backticks. but i have a solution whith open:

    my $output; open PROG, "|my_command -v" or die "canīt exec my_command \n"; while ( <PROG> ){ $output .= $_; }