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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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:

18
19
		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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.

Wish there was more?

I'm considering writing an ebook - click here.

.

Luke is the primary editor of Building Browsergames, and has written a large portion of the articles that you read here. He generally has no idea what to say when asked to write about himself in the third person.

Wednesday, April 23rd, 2008 buildingbrowsergames, code, design, perl
blog comments powered by Disqus

About

Building Browsergames is a blog about browsergames(also known as PBBG's). It's geared towards the beginner to intermediate developer who has an interest in building their own browsergame.

Sponsors

Got Something to Say?

Send an e-mail to luke@buildingbrowsergames.com, or get in touch through Twitter at http://twitter.com/bbrowsergames