user1533198
user1533198

Reputation: 41

perl system call won't recognize paths

I'm trying to execute a system command from a perl program.

It works fine unless I provide a path, when it says " The system cannot find the path specified."

I get the same results with exec(), system(), or backticks.

I get the same results with the command string directly as the argument, or putting it in a single or double-quoted string and passing the string as the argument.

If I copy a non-working command from the perl script and paste it into the DOS box, it works, and vice versa.

For example,

print `cd`;

works fine, but

print `cd \`;

and

print `cd ..`;

give me the same error message.

$cmd = 'foo.htm'; $ret=`$cmd`

starts the browser, but

$cmd = '\foo.htm'; $ret=`$cmd`;

does not.

Does anyone have any suggestions as to what the problem might be?

Upvotes: 4

Views: 2352

Answers (1)

David W.
David W.

Reputation: 107060

It would be helpful if you gave us what your system command was, and what you're getting. It's a bit hard to say what your error is. However, I'll take a guess..

If you're on Windows, and you're doing the \, you must understand that the backslash character is a special quoting character on Perl. To use a real backslash, you need to double it up:

 system ("C:\\Program Files (x86)"\\Microsoft Office\\Word.exe");

Or, even better, use the File::Spec module that comes with Perl. This will guarantee you make the correct path structure:

use File::Spec::Functions;

my $executable = catfile("C:", "Program Files (X86)",
      "Microsoft Office", "Word.exe");
system ($executable);

Of course, you should try to capture the output of the system command to see if there is any error:

my $error = system($executable);
if ($error) {
      if ($? == -1) {
          print "Program failed to execute\n";
      }
      else {
          my $signal = ($? & 127);
          my $exit_code = ($? >> 8);
          print "Error: Signal = $signal  Exit Code = $exit_code\n";
      }
}

Upvotes: 3

Related Questions