1

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";
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
wadesworld
  • 13,535
  • 14
  • 60
  • 93
  • looks ok to me, and works fine on 5.8.9. which version of perl are you using? – Doon Aug 12 '10 at 18:43
  • Works for me under "This is perl, v5.10.1 (*) built for x86_64-linux-gnu-thread-multi" (Ubuntu 10.04.1 LTS). What is your exact host, perl version, is this the complete code? –  Aug 12 '10 at 18:43
  • 2
    Are you sure that `$hostname` is defined in your production code? Are you running with `use warnings; use strict;`? – Eric Strom Aug 12 '10 at 18:43
  • Executed fine here, using perl, v5.10.1 (*) built for x86_64-linux-gnu-thread-multi. Any encoding issues or anything with the text you're testing/comparing to? – signine Aug 12 '10 at 18:45
  • 1
    Are you sure `$hostname` doesn't have some extra whitespace? – mob Aug 12 '10 at 18:50
  • 1
    Have you stripped your $hostname var of all non visible characters? – J.J. Aug 12 '10 at 18:57

2 Answers2

8

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?

Eric Strom
  • 39,821
  • 2
  • 80
  • 152
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • 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. – wadesworld Aug 12 '10 at 18:55
1

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

Charles
  • 11,269
  • 13
  • 67
  • 105