开发者

Is there a way to load a profile inside Perl?

Is there 开发者_C百科a way to load a profile inside Perl?

Like in shell files:

. ~user/.profile


What specifically do you mean by "profile"?

If you mean "retrieve the values of the shell environmental variables that your shell set via .profile", then yes - you do it through a special %ENV hash.

If you mean "read the actual variables set in .profile" like the shell itself does, it's possible but doing it "right" requires either parsing an arbitrary shell script and scrubbing anything that's not an environmental variable assignment, OR executing ". ~/.profile; env`"` and parsing the output.

If you mean "supply a generic configuration to any Perl program that runs via a separate configuration file", you need to add code to those Perl programs to read this configuration file (there are a number of CPAN modules for reading various config files).

If you mean "supply a generic configuration to any Perl program that runs without any special code in those Perl programs to read a separate configuration file, sort of like any shell script gets the stuff from .profile thanks to shell", then the asnwer is "may be". You can leverage PERLOPT environmental variable to supply options which would load up a special module (via -I) containing the configuration that gets set via its "import()". While somewhat doable, it seems like an awful hack that I would strongly recommend against using.


Env::Sourced should do what you need.

use Env::Sourced qw(~/user/profile);
print $ENV{VARAIBLE};


If you have bash configuration values in (or other configuration set up by) a shell script and want that to take effect only for the duration of one execution of a program, you can use a subshell:

( source ~/my_bash_file.sh; perl my_perl_script.pl )

You can access shell environment variables in Perl using the %ENV hash (see the index of Perl's special variables, perldoc perlvar):

my $user = $ENV{USER};
my $home_dir = $ENV{HOME};

Example:

my_bash_file.sh:

#!/bin/bash
export HOME="/home/nowhere"

my_perl_script.pl:

#!/usr/bin/perl
print "the value of HOME is $ENV{HOME}\n";

When executed as perl my_perl_script.pl, my_perl_script.pl prints:

the value of HOME is /home/ether

When executed as ( source ~/my_bash_file.sh; perl my_perl_script.pl ), the output is:

the value of HOME is /home/nowhere


$u=`echo -n ~user`;
open F, "<$u/.profile" || die;
while(<F>)
{print}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜