crusty_collins has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to populate an array and then use the values as variables? Example
my @array = qw(daemon=7500 port=tcp resil=60); foreach my $variable (@array) { print "$variable\n"; # do something to set the variable ($var, $value) = split/=/,$variable; now what? }
AHHHH The $ENV will work just great! Thanks a lot!
for $var (keys %$VARS) { $ENV{$var} = $$VARS{$var}; }
works like a champ!

Replies are listed 'Best First'.
Re: setting envirnment variables from array.
by brian_d_foy (Abbot) on May 20, 2005 at 17:11 UTC

    The "now what" part is to shove the values into the special %ENV hash. See perlvar for the details.

    $ENV{ $var } = $value;
    --
    brian d foy <brian@stonehenge.com>
Re: setting envirnment variables from array.
by mrborisguy (Hermit) on May 20, 2005 at 17:12 UTC

    Your best bet is probably to just put them in a hash.

    my %config; ... $config{ $var } = $value; }

    Then you can access your variables like this:

    $i_want_the_value_of_port = $config{ 'port' };

    -Bryan

Re: setting envirnment variables from array.
by revdiablo (Prior) on May 20, 2005 at 17:13 UTC
    then use the values as variables?

    This question seems to be coming up on a daily basis. The answer is always the same: you really don't want to do it. Use a hash instead:

    my %variables; for (@array) { my ($var, $value) = split /=/; $variables{$var} = $value; }

    Update: ... wow. So I guess 4 of us were all writing our replies at the same time. :-)

Re: setting envirnment variables from array.
by Fletch (Bishop) on May 20, 2005 at 17:13 UTC

    Have a hash %config and store things there ($config{ $var } = $value). If you really want them as real variables you'd need to look for "soft references" in perldoc perlref (but you don't really want to do that; use a hash).

    Update: Hrmm, I missed the envirnment [sic] part of the title. As someone else mentioned, see perldoc perlvar and look for %ENV.

Re: setting envirnment variables from array.
by crusty_collins (Friar) on May 20, 2005 at 18:01 UTC
    Sorry monks, but I should have said that I need to set the name of the var to the var. Confusing, I now but I have a tone of variables that I would just like to iterate through. :) Normally I would go with a hash and extract each var individually.
    $daemon = $config{daemon};
    but what I want to do is iterate through and set them on the fly. So, instead of the above I would like loop and have the var become the actual variable name.
      I hesitate to post any code in support of something considered to be such bad form, but what I think you are asking can be done using soft references. Take note that this sort of thing is frowned upon, as there is almost always a better way to do accomplish the task.