run perl -e from inside perl script in windows
I need to run the following command from inside a Perl script in Windows. The code can't be simpler than this:
#! C:\Perl\bin\perl
perl -e "print qq(Hello)";
I save this file as test.pl
. I open a command prompt in Windows and run the following from the c:\Per\bin
directory. When I run it as perl test.pl
, I get the following result:
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 (i.e. without being inside the file) it works great.
The test.pl
file should contain:
print qq(Hello);
Why would you want to run perl code with perl -e …
? 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.
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.
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. 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 …
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. 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.
I don't know why you need it but:
#!C:\Perl\bin\perl
`perl -e "print qq(Hello)"`;
Why not use eval?
精彩评论