开发者

Use special characters inside perl script for system calls

I'm writing a short installation script in Perl that sets up the user's environmental variables to find certain libraries. I'm using the system() function to set the $PATH variable. However, since that requires the use of the special character $, Perl doesn't like it.

system("export PATH=$PATH:/library/directory/here");

That doesn't do anything because it tries to replace $PATH. When I escape the dollar sign like so:

system("开发者_JAVA技巧export PATH=\$PATH:/library/directory/here");

that doesn't work either.

What can I do?


If you want to update PATH system variable, use this:

$ENV{'PATH'}.=':/library/directory/here';

After this /library/directory/here will be available through PATH for this and all forked processes:

...
system("echo old PATH=$PATH");
$ENV{'PATH'}.=':/library/directory/here';
system("echo new PATH=$PATH");
...


*NIX, unlike Windows, has a separate environment for every process. When you set the PATH via system, it changes it in the sub-process. But then the system command is done, so the its environment is deleted as part of the process clean-up.

Setting the PATH via ENV will set it of the Perl script and all processes forked off of it. It will NOT set the PATH in the shell that runs the script. That has to be done separately via the source command for csh and the dot command, '.', for bash. See man bash for details.


When using double quotes in perl, it replaces variables within the string. Using single quotes perl will not interpret the $ within it.


use single quotes e.g

my $cmd = 'export PATH=$PATH:/library/directory/here';
system($cmd);

Alternatively you can create a bash script that exports PATH variable.
You might also consider to use full path of the script that you trying to call from the Perl instead of calling the program by its name only e.g. use /usr/env/perl instead of perl.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜