You are on page 1of 2

Our Goal, Part 2

Look at our goals again. We need to write three methods for our TutorialConfig module: read, get and set. The first method, read, obviously requires that we tell it what file we want to read. Notice that when we write the source code for this method, we must give it two parameters. The first parameter is the object we're using, and the second is the filename we want to use. We'll use return to indicate whether the file was successfully read.
sub read { my ($self, $file) = @_; my ($line, $section); open (CONFIGFILE, $file) or return 0; # We'll set a special property # that tells what filename we just read. $self->{'_filename'} = $file;

while ($line = <CONFIGFILE>) { # Are we entering a new section? if ($line =~ /^\[(.*)\]/) { $section = $1; } elsif ($line =~ /^([^=]+)=(.*)/) { my ($config_name, $config_val) = ($1, $2); if ($section) { $self->{"$section.$config_name"} = $config_val; } else { $self->{$config_name} = $config_val; } } } close CONFIGFILE; return 1; }

Now that we've read a configuration file, we need to look at the values we just read. We'll call this method get, and it doesn't have to be complex:
sub get { my ($self, $key) = @_; return $self->{$key}; }

These two methods are really all we need to begin experimenting with our TutorialConfig object. Take the module and sample configuration file from above (or download the configuration file here and the module here), put it in a file called tutc.txt, and then run this simple program:

use TutorialConfig; $tut = new TutorialConfig; $tut->read('tutc.txt') or die "Couldn't read config file: $!"; print "The author's first name is ", $tut->get('author.firstname'), ".\n";

(Notice the syntax for calling an object's methods: $object->method(parameters).)

When you run this program, you'll see something like this:
TutorialConfig has been successfully loaded! We just created the variable... and now it's a TutorialConfig object! The author's first name is Doug.

We now have an object that will read configuration files and show us values inside those files. This is good enough, but we've decided to make it better by writing a set method that allows us to add or change configuration values from within our program:
sub set { my ($self, $key, $value) = @_; $self->{$key} = $value; }

Now let's test it out:

use TutorialConfig; $tut = new TutorialConfig; $tut->read('tutc.txt') or die "Can't read config file: $!"; $tut->set('', 'Canada'); print $tut->get('author.firstname'), " lives in ", $tut->get(''), ".\n";

These three methods (read, get and set) are everything we'll need for our module. More complex modules might have dozens of methods!