有人发现此代码有什么问题吗?当我们执行它时(在Linux上),我们直接进入“错误:未知主机”块。
Perl是版本5.8.6
$hostname = "host2";
if ($hostname eq "host1") {
$dbhost = 'dbi:Oracle:dbhost1';
}
elsif ($hostname eq "host2") {
$dbhost = 'dbi:Oracle:dbhost2';
}
elsif ($hostname eq "host3" || $hostname eq "host4") {
$dbhost = 'dbi:Oracle:dbhost3';
}
else {
print "ERROR: UNKNOWN HOST\n";
die "Can't connect";
}
答案 0 :(得分:8)
代码没有问题。但是,使用查找表会更简单(也更灵活):
my $driver = 'dbi:Oracle:';
my %dbihosts = (
host1 => 'dbhost1',
host2 => 'dbhost2',
host3 => 'dbhost3',
host4 => 'dbhost3',
);
my $hostname = "host2";
die "Unknown host '$hostname'" unless exists $dbihosts{ $hostname };
my $dbhost = $dbihosts{ $hostname };
print "$hostname -> $dbhost\n";
$dbh->connect("$driver$dbhost", ...);
PS:您是否忘了chomp $hostname
?
答案 1 :(得分:1)
您的代码没有任何问题。它按预期执行。