loris has asked for the wisdom of the Perl Monks concerning the following question:
Hello,
I'm sure I have asked this before, but I haven't been able to find where, so apologies for possibly repeating myself.
I have a file that contains environment variables. I want to create a new file in which the environment variables have been expanded. I could obviously get the template file line by line, look for things that look like environment variables, look these up in the %ENV hash, and replace the variable with the value if found. E.g.
use strict; use warnings; my $file = shift; my $undefinedVars = 0; open(FILE,$file); while (<FILE>) { if (/(\$[^\/\n\t]*)/) { my $var = $&; my $key = $var; substr($key, 0, 1) = ""; my $val = $ENV{$key}; if (defined($val)) { my $line = $_; $line =~ s/\$//g; $line =~ s/$key/$val/g; print $line; } else { $undefinedVars++; } } else { print $_; } } close(FILE); if ($undefinedVars > 0) { print "ERROR: There were $undefinedVars undefined variables!\n"; }
This input looks (something) like this:
bigcompany.product.part.widgit=$WIDGIT bigcompany.product.part.battery=$BATTERY bigcompany.product.part.frobnicator=$FROBNICATOR bigcompany.product.part.blorpdata=$BLORP/data
But I feel there must be a simpler way. Any ideas?
Thanks,
Update 1: Added code
Update 2: Added input
Update 3: Added missing case to input
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Replacing environment variables
by mantra2006 (Hermit) on Oct 17, 2006 at 13:54 UTC | |
by Hofmator (Curate) on Oct 17, 2006 at 14:00 UTC | |
by Errto (Vicar) on Oct 18, 2006 at 05:00 UTC | |
by loris (Hermit) on Oct 18, 2006 at 06:50 UTC | |
|
Re: Replacing environment variables
by shmem (Chancellor) on Oct 18, 2006 at 10:00 UTC | |
by loris (Hermit) on Oct 18, 2006 at 10:32 UTC | |
by holli (Abbot) on Oct 18, 2006 at 12:54 UTC | |
by loris (Hermit) on Oct 18, 2006 at 14:03 UTC |