One of the nice things about Perl is the huge amount of free codeout there. Available in the form of modules, this code can simplify manycommon tasks while simultaneously offering a powerful toolkit for theexperienced developer. In this article, learn about two of the most popularPerl modules: DBI, used for database connectivity, and Carp, used tosimplify error handling.
I'll begin with the DBI, a database-independent software interface for Perl. As the name suggests, it's a layer of abstraction over the actual database access methods and allows developers to deal with different databases without radically altering their code on a per-database basis. As long as a "DBI drive" (aka DBD) exists for the database in question, you're home free!
By placing a layer of abstraction between the database and the developer, the DBI insulates the programmer from database implementation details. If you initially write a script to talk directly to, say, Oracle and later need to have it work with another database server, you will usually have to rewrite all the database-specific parts. If you use a database API like the DBI, you can port your script over with very little surgery required.
The DBI by itself is not responsible for the interaction between the database and a Perl script. It simply provides a consistent interface to the underlying DBD (which does the actual work). It is the DBD which actually "talks" to the database, not the DBI. When a function call is made from within DBI, it actually transmits the properly-formatted information over to the relevant DBD. Once the DBD is through, it picks up the response and returns it to the caller.
The DBI is also responsible for maintaining a clean interface, handling the automatic loading of DBDs, error checking, and so on. Acting like a middleman, it deals with everything specific to a particular database, thereby allowing the underlying implementation to change without the developer having to worry about it.
There exist DBDs for most popular databases, including MySQL, PostgreSQL, Oracle and others. There's even an ODBC DBD, which can be used to connect to Microsoft databases like Access.
This article copyright Melonfire 2001. All rights reserved.