in reply to Replacing environment variables

Good thing you updated your post with code. May we have a look at a sample input file too?
if (/(\$[^\/\n\t]*)/) {

What if the presumed variable is $f.`rm -rf $ENV{HOME}`? Oops. Lotsa space now..

my $var = $&; my $key = $var; substr($key, 0, 1) = "";

You capture your match with () and then use $&? And what do you have $var for? Why not $key = $1?

Leave the the $ out of your capturing parens. That way you haven't got to strip it with substr.

I'd write your loop as

while(<FILE>) { if (my ($key) = /\$(\w+)/) { defined($ENV{$key}) and s/\$$key/$ENV{$key}/ or $undefinedVars++; } print; }

but it's usefulness depends on the input file...

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

Replies are listed 'Best First'.
Re^2: Replacing environment variables
by loris (Hermit) on Oct 18, 2006 at 10:32 UTC

    Thanks for your reply. I have updated the OP with some sample input, which is, as you see, rather simple. I realised that the capturing the $ and then removing it is a bit silly, but when I moved the $ out of the capturing brackets, the match failed, so obvioulsy I have to escape the $ in some other way. You are right of course about not then needing two variables, one with the $ and one without.

    loris


    "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 . . ."
      while (<DATA>) { # match any dollar followed by a number # of non whitespaces (unicode safe) # and replace it by then corresponding # environment variable if ( s/\$(\P{IsSpace}+)/$ENV{$1}/ ) { $undefinedVars++ unless $ENV{$1}; } print; } if ( $undefinedVars > 0) { print "\n\nERROR: There were $undefinedVars undefined variables!\n +"; } __DATA__ bigcompany.product.part.path=$PATH bigcompany.product.part.widgit=$WIDGIT bigcompany.product.part.battery=$BATTERY bigcompany.product.part.frobnicator=$FROBNICATOR


      holli, /regexed monk/

        Thanks for the nice concise solution, holli. Looking at it, I realise that I have missed out the case where the environment variable represents a directory and may be followed by a subdirectory (see updated OP). Thus the regexp would have to be a little different.

        loris


        "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 . . ."