Evaluating environment variables

P

prattm

I am reading in a config file that has a bunch of absolute file paths,
most with embedded environment variables, such as:

${HOME}/bin/myscript.pl

To ultimate goal is to do some file tests on these items, specifically
readlink, but I can't because of the embedded env variables. So I
thought I would try a nifty little search and replace:

$file =~ s/\${/\$ENV{/;

The goal being the replace all occurences of "${" with "$ENV{" so that
Perl will resolve the env variables for me using the ENV hash. The
search and replace works, but I still get errors passing in the new
variable to readlink because Perl is not evaluating the $ENV{...}
substrings first.

Any ideas of how to get around this? My fallback is to just do
something like

$file = `echo $file`;

But this seems a bit goofy to me and it seems like there ought to be a
way to do in Perl.

Thanks, Mike
 
U

Uri Guttman

GJ> Assuming you have braces around all your variable names:

GJ> s/\${(.*?)}/$ENV{$1}/eg

you don't need /e as the replacement there is a valid string and doesn't
need to be evaled. and you will likely need to escape the { as perl will
interpret {} as a quantifier. i haven't tested that and i leave that as
an exercise to the OP.

uri
 
P

prattm

Thanks for the replies. Glenn's suggestion did work as is, although I
have yet to try it without the /e modifier.

Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top