Building Browsergames: Using Configuration Files (Perl)

For those of you who are writing Perl, you might be wondering about how you can implement the simple configuration file system that I explained how to build in PHP yesterday.

If you’re looking for more advanced configuration options than the typical configuration file, you might want to try searching The CPAN for configuration modules – there are a wealth of configuration file modules that will give you as much(or as little) extensability as you want.

However, if you’re looking to roll your own, here’s how to do it.

First, we will create the configuration file. Save this as config.pm:

 

package config;
 
use Exporter;
our @ISA = qw(Exporter);
 
our %config;
our @EXPORT = qw($dbhost $dbname $dbuser $dbpass);
 
$dbhost = 'localhost';
$dbname = 'db_name';
$dbuser = 'user';
$dbpass = 'password';
 
1;

And then to use it inside our registration page from earlier, we would just adjust the code from register.cgi:

use config;
		my $dbh = DBI->connect("DBI:mysql:$dbname:$dbhost",$dbuser,$dbpass,{RaiseError => 1});

At this point, we’ll have exactly the same behavior as the PHP example – you just need to use the module that you created to store your configuration settings – by adding the names of our configuration variables to @EXPORT, they get automatically exported into the program that’s using them. And that’s all there is to it! Now your database settings are all stored in one place, so you should have no trouble changing them if you ever need to.

As a bit of an aside, I usually like to store my configuration data in a hash:

 

package config;
 
use Exporter;
our @ISA = qw(Exporter);
 
our %config;
our @EXPORT = qw(%config);
 
%config = (
	dbHost	=>	'localhost',
	dbName	=>	'db_name',
	dbUser	=>	'user',
	dbPass	=>	'password',
);
 
1;

But that’s just the way I like to do it – your mileage may vary, and ultimately whatever approach works best for you is the one you should use.