moshefr has asked for the wisdom of the Perl Monks concerning the following question:

I was given the task of accepting a file containing lines which might have one or occurrences of Environment variables defined as ${VAR}. I have to translate within the file all those variables into the environment variable which is defined. My solution was:

perl -i -n -e ' while ($_ =~ /\${([^\$]*)}/g) { $s = "\\" . $&; $t = $ENV{$+}; s/$s/$t/e; } print $_;' file
Is there an better way?
moshefr

20040517 Edit by Corion: Added formatting

Replies are listed 'Best First'.
Re: Translating Env Variables
by Abigail-II (Bishop) on May 17, 2004 at 09:04 UTC
    I think your regex will fail on a line like this:
    Hello, ${world}, {Oops}
    Where is your file coming from? Do you have to expand variables like the shell does? Then there's a lot more than just ${VAR}.

    Abigail

      Thanx for the reply, the file format would not allow such a format as you mentioned. The script just has to translate the mentioned variables as that is the forced format
Re: Translating Env Variables
by Anonymous Monk on May 17, 2004 at 10:15 UTC
    Maybe I'm missing something but wouldn't s/\${([^\$]*)}/$ENV{$1}/g; do it?
Re: Translating Env Variables
by revdiablo (Prior) on May 17, 2004 at 19:25 UTC

    Instead of [^\$]* for the character class, I would think about using [^}]* instead. The reason is demonstrated by Abigail-II's post. If there is more than one '}' on any given line in your input file, then your regular expression will gobble everything up until the last one. using [^}] will make it stop at the first '}' character it finds.

      Or depending on the OP's requirements, a simple \w+ might be easiest and best.