in reply to Parsing variables from login scripts

It's not too difficult... you just need split and a regex check. Something like the following is untested but conceptually fairly sound:
while (<INPUT>) { chomp; my ($var, $value) = split(/\s*=\s+/, $_, 2); if ($value =~ s/^\$(\w+)//) { # $value .= $env_var{$1} || ''; $value = $env_var{$1} . $value; } $env_var{$var} = $value; }
You could make that shorter, but you could also add better checking to make it better. Jellybean actually does this in Jellybean::Config, so I know I've written it correctly at least once before.

Update: Don't work and post. Fastolfe is correct, and I've updated my code to work.

Replies are listed 'Best First'.
RE: Re: Parsing variables from login scripts
by eLore (Hermit) on Jul 28, 2000 at 18:55 UTC
    I've been working way too many hours to see this clearly. Here's what's not working so well, so far... Ok, let's see if I can format this correctly:
    ___DATA___ MY_DIR=~/temp/module export MY_DIR MY_BIN=$MY_DIR/bin MY_DATA=$MY_DIR/data export MY_BIN MY_DATA __temp.pl__ #! /usr/local/bin/perl require "testpack.pm"; testpack::import(); print "DIR $DIR\n"; __testpack.pm__ package testpack; sub import { $conf_file = "conf.sh"; open (FILE, $conf_file) || die "Cant open file. \n"; while (<FILE>) { if (! (/^\W/ || /^export/)) { # ign. cmnts & ws chomp; print "$_\n"; my ($var, $value) = split(/\s*=\s+/, $_, 2); if ($value =~ s/^\$(\w+)//) { $value .= $env_var{$1} || ''; } $env_var{$var} = $value; my ($caller_package) = caller; *{"${caller_package}::${var}"} = $value; } # end if } # end while } # END import() definition
      Your split doesn't match your data -- the whitespace before the = is optional (zero or more instances) but required after the sign (one or more instances). Change the + to a * and it will probably work better.

      You might put a debugging line after the split, just to see what's in $var and $value: print "\$var is ->$var<-\t\$value is ->$value<-\n"; Besides that, I had things backwards in the original version of my code. Try this instead: $value = $env_var{$1} . $value; That way, it won't go in the wrong place. Oops!

RE: Re: Parsing variables from login scripts
by Fastolfe (Vicar) on Jul 28, 2000 at 19:34 UTC
    Shell-style variable interpolation has been discussed in recent nodes. The one you have above won't work at all like you seem to expect.

    PATH = /someplace PATH = $PATH:/somewhere/else
    In this case, $env_var{PATH} would equal ":/somewhere/else/someplace".

    I'm afraid I can't find the original thread, but a fairly robust regular expression looked something like this:

    $value =~ s/$({?)(\w+)(?(1)})/$env_var{$2}/eg;
    This would interpolate stuff like $PATH, ${PATH}, etc.