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,

loris

Update 1: Added code

Update 2: Added input

Update 3: Added missing case to input


"It took Loris ten minutes to eat a satsuma . . . twenty minutes to get from one end of his branch to the other . . . and an hour to scratch his bottom. But Slow Loris didn't care. He had a secret . . ."

In reply to Replacing environment variables by loris

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.