-   Programming (
-   -   Perl with bash environment vars (

rose_bud4201 06-19-2006 05:22 PM

Perl with bash environment vars
I've got a perl script which needs to be aware of bash environment variables. I can use Env, but the problem is not all of the variables exist for the user that the script will be running as.

In bash, we accomplish this by having a shell script called which does a whole bunch of 'export VARIABLE=VALUE' calls.

Our shell scripts, then, do:

source /path/to/
db2 "connect to $db user $user using $blah"

What I need to do is that same thing, only in perl. `source /path/to/` gives me a "no such command as source" error message, and `. /path/to/` followed by "my $dbname = $VARIABLE" (where $VARIABLE is one of those exported in doesn't error, but doesn't seem to do anything either.

I still get

$ ./
Global symbol "$VARIABLE" requires explicit package name at ./ line 33.

Execution of ./ aborted due to compilation errors.

Does anyone know how to work around this? I'm really not supposed to simply parse the env file, since its format has been known to change at will.


spirit receiver 06-19-2006 06:17 PM

I guess you'll have to set those environment variables in ~/.profile or in /etc/profile, or instead of invoking that Perl script directly, you can use a shell script that sets the variables and then proceeds with the Perl script.

puffinman 06-20-2006 01:23 PM

You can easily parse the file yourself. Here's one way to do it.

The input file:

export STUFF=things
export  LOOKIT=here
export SNAZZY=eh

The perl script:


my $varfile = "vartest";
my %vars;

open(FH,"<$varfile") or die "Couldn't open $varfile: $!\n";
while (<FH>) {
  if (m/export\s+(\w+)=(.+)$/) {
close FH;

use Data::Dumper;
print Dumper %vars;

The output:

$VAR1 = 'STUFF';
$VAR2 = 'things';
$VAR4 = 'eh';
$VAR6 = 'here';

rose_bud4201 06-21-2006 11:05 AM

Hmm...I may go the shell script route, rather than the parsing route. It's for work, and there are just things which I am and am not supposed to do :)

Thanks to both of you!

spirit receiver 06-21-2006 11:30 AM

You can use the following construct, to make sure the Perl script won't be invoked independently:

#! /bin/bash

export NEW_VAR="nonsense"

exec perl <<EOF

# Here starts your Perl script
print join(",",sort( keys(%ENV)));


rose_bud4201 06-21-2006 01:03 PM

Hmmm..that's a neat trick! I never would've thought of it, thank you :)

I'll check back and let you know how it works.

rose_bud4201 06-21-2006 01:19 PM

Hurrah, success! I used a hybrid method:

# Set some environment variables that needs,
# and then call the script.

source /usr/local/bin/

echo "\$1 is: $1\n"
echo "\$2 is: $2\n"
echo "\$3 is: $3\n"
echo "\$4 is: $4\n"

/home/me/work/ $1 $2 $3 $4

It works, and outputs the correct variable values from inside the perl script.
Thanks so much!

All times are GMT -5. The time now is 04:36 PM.