Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: setting env vars from hash fails for me

by ccarden (Monk)
on Aug 07, 2003 at 15:35 UTC ( [id://281929]=note: print w/replies, xml ) Need Help??


in reply to setting env vars from hash fails for me

Okay, it was a combination of chromatic's and japhy's suggestions which got me working. But it wasn't until I read every response that I understood all of the things that I was doing wrong.

First, though, chromatic suggested %ENV{ keys %hash } = values %hash; which I tried right away, only to get a syntax error. Not certain what was failing, I went to japhy's suggestion and came up with:

foreach $key (keys %hash) { $ENV{$key} = $hash{$key}; }
This works perfectly. But why doesn't chromatic's example work?

As for all of the other suggestions, they mostly had to do with my clumsy creation of the hash. My example code was significantly simpler than what I'm really doing, and I was trying provide you with a simple hash for testing. It was the use Env qw(keys %hash); that was really the hack, and it turns out that I misread an example somewhere on this site that was meant for multi-valued vars (thanks for the heads-up, PodMaster).

My real code takes in the hash as a parm using Getopt and then passes it to a sub intended to set the environment vars to their corresponding values in the hash:

#!/usr/bin/perl use strict; use warnings; use Getopt::Long; my %engEnvVars; GetOptions ( "engEnvVar=s" => \%engEnvVars ) sub setEnvVars { my %engEnvVars = @_; my $key; foreach $key (keys %hash) { $ENV{$key} = $hash{$key}; } system("printenv") if $DEBUG; } setEnvVars(%engEnvVars);
and then call the script with parms:
./testScript.pl -engEnvVar APP_DIR=/usr/vendor/app/version/ -engEnvVar + TMP_DIR=/usr/tmp/
... etc.

Yes, dws was correct in that I am setting these environment variables so that I can call another application.

I tested chromatic's second example:

use strict; %ENV = ( foo => 'bar '); system ( 'printenv' );
... and found that in that case printenv only prints out the one environment variable and its value. In my main script, printenv prints out not only the vars that I set in my script, but all other environment vars. Curious.

What a long, arduous path for me. Finding this site and sharing my questions shows me how little I really know about Perl. I appreciate all of your input. Thank you.

-- ccarden

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://281929]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2024-03-29 09:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found