perlstringflow-control

Perl elsif not being evaluated


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

Solution

  • 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?