views:

79

answers:

2

Anyone see anything wrong with this code? When we execute it (on Linux), we get taken straight to the "Error: Unknown host" block.

Perl is version 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";
}
+1  A: 

There's nothing wrong with your code. It executes as expected for me.

Charles
I'd verify that $hostname is really 'host2' when you think it is.
edebill
+8  A: 

There is nothing wrong with the code. However, using a lookup table would be simpler (and more flexible):

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: Did you forget to chomp $hostname?

Sinan Ünür
Arggh....the missing chomp was indeed the problem. However, why does the debugger never show any of the other elsif clauses being evaluated? It just skips straight to the else.
Wade Williams