You are on page 1of 2

Beginners Intro to Perl - Part 5

So far, we've mostly stuck to writing everything for our programs ourselves. One of the big advantages of Perl is that you don't need to do this. More than 1,000 people worldwide have contributed more than 5,000 utility packages, or modules, for common tasks. In this installment, we'll learn how modules work by building one, and along the way we'll learn a bit about object-oriented programming in Perl.
What Is an Object?

Think back to the first article in this series, when we discussed the two basic data types in Perl, strings and numbers. There's a third basic data type: the object. Objects are a convenient way of packaging information with the things you actually do with that information. The information an object contains is called its properties, and the things you can do with that information are called methods. For example, you might have an AddressEntry object for an address book program - this object would contain properties that store a person's name, mailing address, phone number and e-mail address; and methods that print a nicely formatted mailing label or allow you to change the person's phone number. During the course of this article, we'll build a small, but useful, class: a container for configuration file information.
Our Goal

So far, we've put the code for setting various options in our programs directly in the program's source code. This isn't a good approach. You may want to install a program and allow multiple users to run it, each with their own preferences, or you may want to store common sets of options for later. What you need is a configuration file to store these options. We'll use a simple plain-text format, where name and value pairs are grouped in sections, and sections are indicated by a header name in brackets. When we want to refer to the value of a specific key in our configuration file, we call the key section.name. For instance, the value of author.firstname in this simple file is ``Doug:''
[author] firstname=Doug lastname=Sheppard [site] name=Perl.com url=http://www.perl.com/

(If you used Windows in the ancient days when versions had numbers, not years, you'll recognize this as being similar to the format of INI files.)

Now that we know the real-world purpose of our module, we need to think about what properties and methods it will have: What do TutorialConfig objects store, and what can we do with them? The first part is simple: We want the object's properties to be the values in our configuration file. The second part is a little more complex. Let's start by doing the two things we need to do: read a configuration file, and get a value from it. We'll call these two methods read and get. Finally, we'll add another method that will allow us to set or change a value from within our program, which we'll call set. These three methods will cover nearly everything we want to do.

You might also like