Database Reference
In-Depth Information
$dsn .= ";database=$db_name" if defined ( $db_name );
$dsn .= ";mysql_socket=$socket_file" if defined ( $socket_file );
$dsn .= ";port=$port_num" if defined ( $port_num );
return DBI -> connect ( $dsn , $user_name , $password , $conn_attrs );
}
1 ; # return true
The module encapsulates the code for establishing a connection to the MySQL server
into a connect() method, and the package identifier establishes a Cookbook namespace
for the module. To invoke the connect() method, use the module name:
$dbh = Cookbook:: connect ();
The final line of the module file is a statement that trivially evaluates to true. (If the
module doesn't return a true value, Perl assumes that something is wrong with it and
exits.)
Perl locates library files by searching the list of directories named in its @INC array. To
check the default value of this variable on your system, invoke Perl as follows at the
command line:
% perl -V
The last part of the output from the command shows the directories listed in @INC . If
you install a library file in one of those directories, your scripts will find it automatically.
If you install the module somewhere else, tell your scripts where to find it by setting the
PERL5LIB environment variable, as discussed in the introductory part of this recipe.
After installing the Cookbook.pm module, try it from a test harness script, harness.pl :
#!/usr/bin/perl
# harness.pl: test harness for Cookbook.pm library
use strict ;
use warnings ;
use Cookbook ;
my $dbh ;
eval
{
$dbh = Cookbook:: connect ();
print "Connected\n" ;
};
die "$@" if $@ ;
$dbh -> disconnect ();
print "Disconnected\n" ;
harness.pl has no use DBI statement. It's unnecessary because the Cookbook module itself
imports DBI; any script that uses Cookbook also gains access to DBI.
Search WWH ::




Custom Search