简体   繁体   English

从windows中的perl脚本运行perl -e

[英]run perl -e from inside perl script in windows

I need to run the following command from inside a Perl script in Windows. 我需要从Windows中的Perl脚本中运行以下命令。 The code can't be simpler than this: 代码不能比这更简单:

#! C:\Perl\bin\perl

perl -e "print qq(Hello)";

I save this file as test.pl . 我将此文件保存为test.pl I open a command prompt in Windows and run the following from the c:\\Per\\bin directory. 我在Windows中打开命令提示符并从c:\\Per\\bin目录运行以下命令。 When I run it as perl test.pl , I get the following result: 当我以perl test.pl运行它时,我得到以下结果:

C:\Perl\bin>perl test.pl
syntax error at test.pl line 3, near ""perl -e "print"
Execution of test.pl aborted due to compilation errors.

How can I fix this? 我怎样才能解决这个问题? If I just run perl -e from the command prompt (ie without being inside the file) it works great. 如果我只是从命令提示符运行perl -e (即不在文件中),它的效果很好。

test.pl文件应包含:

print qq(Hello);

Why would you want to run perl code with perl -e … ? 为什么要用perl -e …运行perl代码? Just put the actual code in your program. 只需将实际代码放入程序中即可。

If, on the other hand, you want to run an external command from within your program, then the answer depends on what you want to do with the input/output and/or the exit code of your program. 另一方面,如果要从程序中运行外部命令,则答案取决于您要对程序的输入/输出和/或退出代码执行的操作。 Have a look at system , qx and open . 看看系统qxopen

To run another program from your Perl program, use the system operator that has a nice feature for bypassing the command shell's argument parsing. 要从Perl程序运行另一个程序,请使用具有良好功能的system运算符来绕过命令shell的参数解析。

If there is more than one argument in LIST, or if LIST is an array with more than one value, starts the program given by the first element of the list with arguments given by the rest of the list. 如果LIST中有多个参数,或者LIST是具有多个值的数组,则使用列表其余部分给出的参数启动列表的第一个元素给出的程序。 If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing … 如果只有一个标量参数,则检查参数是否为shell元字符,如果有,则将整个参数传递给系统的命令shell进行解析...

For example: 例如:

#! perl

system("perl", "-le", "print qq(Hello)") == 0
  or warn "$0: perl exited " . ($? >> 8);

Remember that system runs the command with its output going to the standard output. 请记住, system运行命令,其输出将转至标准输出。 If you want to capture the output, do so as in 如果要捕获输出,请执行以下操作

open my $fh, "-|", "perl", "-le", "print qq(Hello)"
  or die "$0: could not start perl: $!";

while (<$fh>) {
  print "got: $_";
}

close $fh or warn "$0: close: $!";

As with system , opening a command specified as a multi-element list bypasses the shell. system ,打开指定为多元素列表的命令会绕过shell。

I don't know why you need it but: 我不知道为什么你需要它但是:

#!C:\Perl\bin\perl

`perl -e "print qq(Hello)"`;

为什么不使用eval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM