echo does not work for PATH variable!
When I run the ls
command this runs fine. But echo $PATH
does not give me any output from perl. When I run ec开发者_运维技巧ho
from the shell prompt it gives me output. Can you explain this behavior?
#!usr/bin/perl
$\="\n";
$out = `ls`;
print $out;
$out=`echo $PATH`;
print $out;
Please note that while the technically correct answer to your question is the $
interpolation, you should also note that you should not treat Perl like a shell script and call external commands via backticks instead of using Perl built-in or library functions designed for the purpose:
$out = join("\n", glob("*")); # same as `ls`
$out = $ENV{PATH}; # same as `echo $PATH`
This has several significant advantages:
- speed (no call to system)
- portability
- More security (no shell attack vector)
- Most built ins cover proper error handling for you better than your own system call implementation
- Nearly always a better, cleaner, shorter and easier to read/maintain code
Backticks interpolate like double quotes, so you need to escape the $
.
$out=`echo \$PATH`;
$PATH
is shell variable, from perl you should use it as perl variable $ENV{PATH}
Still try to read some basic docs too, like perldoc perlintro
. No need for executing echo
at all.
Perl is interpolating $PATH in the backticks as a Perl variable, and you've not set a $PATH anywhere in your script, so the command is coming out as
$out = `echo `
which is basically a null-op. Try
$out = `echo \$PATH`
instead, which would force Perl to ignore the $ and pass it intact to the shell.
You need to escape $
in $PATH
because the backticks operator interpolates any variables.
$out=`echo \$PATH`;
You could also use qx//
with single quotes. From perldoc perlop:
Using single-quote as a delimiter protects the command from Perl's double-quote interpolation, passing it on to the shell instead:
- $perl_info = qx(ps $$); # that's Perl's $$
- $shell_info = qx'ps $$'; # that's the new shell's $$
Others have already explained the reason - variables inside backticks are interpolated, so your echo $PATH
is actually becoming echo
since there's no $PATH
variable declared.
However, always put use strict;
at the top of every Perl script you write.
Had you done so, Perl would have told you what was happening, e.g.:
Global symbol "$PATH" requires explicit package name at myscript.pl line 9
To stop variables being interpolated, either escape them (e.g. \$PATH
), or, more cleanly, use e.g. qx'echo $PATH'
.
Also, as others have pointed out, calling echo $PATH
makes no real-world sense; if you're trying to get the contents of the PATH environment variable, just use $ENV{PATH}
- however, you may have just been using it as a simple reduced demonstration case.
精彩评论