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:

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. you'll see something like this: TutorialConfig has been successfully loaded! We just created the variable. $tut->get('author. get and set) are everything we'll need for our TutorialConfig. $tut->read('tutc. $key.txt') or die "Couldn't read config file: $!".country'). $value) = @_. $tut->get('author. These three methods (read. $tut = new TutorialConfig. $tut->read('tutc. 'Canada'). ". ". (Notice the syntax for calling an object's methods: $object->method(parameters). " lives in ". print "The author's first name is ".txt') or die "Can't read config file: $!".firstname').firstname'). $tut = new TutorialConfig. and now it's a TutorialConfig object! The author's first name is Doug. print $tut->get('author.\n".pm module. $tut->set(''..\n". } Now let's test it out: use TutorialConfig. We now have an object that will read configuration files and show us values inside those files.) When you run this program. More complex modules might have dozens of methods! .use TutorialConfig. $self->{$key} = $value.