Just somewhere to keep my notes while I'm playing.

Thursday, October 8, 2009

Perl: Connection Details in a Subroutine

This example moves the connection information out of the main flow of the program and in to a subroutine. Notice that I have declared the hash %mydbinfo twice. This is because in both cases they are declared as lexically scoped (using 'my'). This means that the %mydbinfo that we see in the subroutine is a totally sepoerate variable from the %mydbinfo in the main body of the code. If like me you earned your living writing COBOL in the 80's this may seem strange - why would you want to do this. The answer is taht it makes it very clear what the scope of the variable is and who can see it. You can define global variables, but it's considered good practice to limit the scope of variables as tightly as possible whilst still achieving your goals.

#!/usr/bin/perl
use strict;
use DBI();

sub dbinfo() {
 my %mydbinfo = ( db => "cddb",
    host => "localhost",
    user => "myuser",
    passwd => "xxx"
 );
 return %mydbinfo;
}
  
my %mydbinfo = dbinfo();
my $dbconnect = "DBI:mysql:database=" . $mydbinfo{db} . ";host=" . $mydbinfo{host} ;

my $dbh1 = DBI->connect($dbconnect,$mydbinfo{user}, $mydbinfo{passwd}, { raiseError => 1, AutoCommit => 0 })
|| die "Database connection not made: $DBI::errstr";
my $sql = "SELECT artist.name, cd.title FROM artist, cdtable AS cd WHERE artist.id = cd.artid";
my $sth = $dbh1->prepare($sql);

$sth->execute();

my( $name, $title );
$sth->bind_columns( \$name, \$title );

print "Name\t\tTitle\n";
while( $sth->fetch() ) {
        print "$name\t$title\n";
}
$dbh1->disconnect() if($dbh1)

No comments: