How can i acces shell environment variables in a Perl script

400 Views Asked by At

What i have

I have a Perl script that check connection to oracle database .Here is my code

#!/usr/bin/perl
use DBI;
my $ORACLE_SID =  $ENV{'ORACLE_SID'};
$\="\n";
print "exported variable=$ORACLE_SID";
print "Connecting to DB..";
my $dbh = DBI->connect('dbi:Oracle:host=oracle;sid=$ORACLE_SID;port=1521', 'books_admin/MyPassword', '',{ RaiseError => 1, AutoCommit => 0 })or die print ("could not connect! $DBI::errstr \n");

I have exported ORACLE_SID by export ORACLE_SID=ORCLCDB The output of this code is

    exported variable=ORCLCDB
    Connecting to DB..
    DBI connect('host=oracle;sid=$ORACLE_SID;port=1521','books_admin/MyPassword',...) failed: ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach) at perl.pl line 8. 

Seems like ORACLE_SID is picked up by Perl but it is not used in sid=$ORACLE_SID. Why print function can use $ORACLE_SID and sid=$ORACLE_SID can't fetch the value

1

There are 1 best solutions below

1
On BEST ANSWER
print "exported variable=$ORACLE_SID";

This works because you have a double-quoted string. And variables are expanded in doubled-quoted strings.

my $dbh = DBI->connect('dbi:Oracle:host=oracle;sid=$ORACLE_SID;port=1521', 'books_admin/MyPassword', '',{ RaiseError => 1, AutoCommit => 0 })or die print ("could not connect! $DBI::errstr \n");

Here, your $ORACLE_SID is inside a single-quoted string. And variables are not expanded in single-quoted strings. You need to change:

'dbi:Oracle:host=oracle;sid=$ORACLE_SID;port=1521'

to:

"dbi:Oracle:host=oracle;sid=$ORACLE_SID;port=1521"