James Mclaren
James Mclaren

Reputation: 674

Environment variables not working in Perl

I am trying to set some environment variables in Perl at the very beginning of the program, but I keep receiving errors unless I set them in a Bash script that calls my Perl script.

#!/usr/bin/perl -w
$ENV{'ORACLE_HOME'}='path';
$ENV{'LD_LIBRARY_PATH'}='path';

This does not work, but my shell script does:

#!/bin/bash
export ORACLE_HOME=path
export LD_LIBRARY_PATH=path
./perlscript.pl

I am setting these paths in order to get my DBI module to work. Ideally, I would like to set the paths in the Perl script and not use a Bash script.

Error:

Install_driver (Oracle) failed: Can't load /some/path/ for module DBD:Oracle: libclntsh.so.11.1: Cannot open shared object file: No such file or directory at /some/path/DynaLoader.pm line 230

Code

use DBI;
my $dbh = DBI->connect("DBI:Oracle:host=something;port=something;sid=something");
my $sth = $dbh->perepare($query);
$sth->execute();
$sth->finish();

Upvotes: 1

Views: 7536

Answers (3)

Mak_Thareja
Mak_Thareja

Reputation: 177

When Perl gets started it makes it own sub shell. That sub shell does not contain all features, like sourcing a shell file which is available only for main shells. You can not set or export any environment path for your main shell from Perl.

You can use your Bash file to get the environment paths in Perl external module from CPAN which is Shell::Source.

$env_path= Shell::Source->new(shell=>"tcsh",file=>"../path/to/file/temp.csh");
$env_path->inherit;
print "$ENV{ORACLE_HOME}";
print "$ENV{LD_LIBRARY_PATH}";

For more information, you can search on CPAN.org regarding relevant modules.

Upvotes: 0

ikegami
ikegami

Reputation: 386331

IIRC, it's because the C library makes it own copy of the environment and/or because LD_LIBRARY_PATH is used when the executable is loaded. Workaround:

#!/usr/bin/perl -w
if (!$ENV{ORACLE_HOME}) {
    $ENV{ORACLE_HOME} = 'path';
    $ENV{LD_LIBRARY_PATH} = 'path';
    exec($^X, '--', $0, @ARGV);
}
...

In case I'm wrong, try the following first. It makes sure the environment vars are set before the modules that use them are loaded.

#!/usr/bin/perl -w
BEGIN {
    $ENV{ORACLE_HOME} = 'path';
    $ENV{LD_LIBRARY_PATH} = 'path';
}
...

Upvotes: 6

user1919238
user1919238

Reputation:

Your problem may be that modules are included in the compilation phase, before you actually set those environment variables.

If so, it should work if you put them inside a BEGIN { ... } block.

#!/usr/bin/perl -w
BEGIN
{
    $ENV{'ORACLE_HOME'}='path';
    $ENV{'LD_LIBRARY_PATH'}='path';
}

Upvotes: 3

Related Questions