我如何在 Perl 脚本中访问 shell 环境变量

How can i acces shell environment variables in a Perl script

我有什么

我有一个 Perl 脚本来检查与 oracle 数据库的连接。这是我的代码

#!/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");

我已通过 export ORACLE_SID=ORCLCDB 导出 ORACLE_SID 这段代码的输出是

    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. 

似乎 ORACLE_SID 被 Perl 使用,但它没有在 sid=$ORACLE_SID 中使用。 为什么print函数可以用$ORACLE_SID而sid=$ORACLE_SID取不到值

print "exported variable=$ORACLE_SID";

这是有效的,因为你有一个双引号字符串。并且变量在双引号字符串中展开。

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");

在这里,您的 $ORACLE_SID 在单引号字符串中。并且变量不会在单引号字符串中展开。您需要更改:

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

至:

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