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
In reply to Replacing environment variables by loris
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |