这个perl代码有什么问题?

时间:2013-06-14 09:00:30

标签: windows perl system

我试图使用perl在系统命令提示符下运行一组命令。

这是代码

#!/usr/local/bin/perl -w

use strict;

print_prompt();


sub print_prompt {
print "What's your name?";
  system("G:\");
system("cd Documents and Settings/Administrator/eworkspace/Sample");
  print `ant`;

}

但这会让我跟着错误

Bareword found where operator expected at execute.pl line 11, near "system("cd"
 (Might be a runaway multi-line "" string starting on line 10)
String found where operator expected at execute.pl line 11, at end of line
    (Missing semicolon on previous line?)
syntax error at execute.pl line 11, near "system("cd Documents "
Can't find string terminator '"' anywhere before EOF at execute.pl line 11.

我该如何解决这个问题?这段代码可能有什么问题?我是否需要指明空格?

2 个答案:

答案 0 :(得分:6)

这两行:

system("G:\");
system("cd Documents and Settings/Administrator/eworkspace/Sample");

以两种方式被打破。首先,最重要的是以其他人在我面前描述的方式打破。 \转义",因此它不会关闭引用的字符串,并且文件其余部分的语法也会被破坏。

但其次,这两条线都以更深的方式被打破。他们不按你的想法行事。实际上他们都有效地做了什么。 system命令调用一个新的shell环境来运行该命令。新环境从父环境(运行代码的环境)继承值。这些值包括当前目录。然后,在新的子环境中更改当前目录。但是当system命令完成(立即发生)时,您的新环境将被销毁。您的程序将继续在原始环境中使用原始当前目录运行。

你应该看看Perl的内置chdir函数。

答案 1 :(得分:1)

问题在于:

system("G:\");
  1. 这不是一个明智的命令。
  2. 反斜杠正在转义",所以字符串实际上是

    "G:\");
    system("
    

    qq{G:");\nsystem(}使用备用分隔符。

    字符串必须来自某种形式的运算符,但cd不是一个。

  3. 解决方案:永远不要使用反斜杠作为路径分隔符,它们只会导致问题。并删除奇怪的G:\命令,它甚至应该做什么?

    要在字符串中包含文字反斜杠,您必须将其转义:\\