What Object Can Do

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

What Does Our Object Do?

Before we can create an object, we need to know how to create it. That means we must write a method called new that will set up an object and return it to us. This is also where you put any special initialization code that you might need to run for each object when it is created. The new method for our TutorialConfig class looks like this, and goes into TutorialConfig.pm right after the package declaration:
sub new { my ($class_name) = @_; my ($self) = {}; warn "We just created our new variable...\n "; bless ($self, $class_name); warn "and now it's a $class_name object!\n"; $self->{'_created'} = 1; return $self; }

(Again, you won't need those warn statements in actual practice.) Let's break this down line by line. First, notice that we define methods by using sub. (All methods are really just a special sort of sub.) When we call new, we pass it one parameter: the type of object we want to create. We store this in a private variable called $class_name. (You can also pass extra parameters to new if you want. Some modules use this for special initialization routines.) Next, we tell Perl that $self is a hash. The syntax my ($self) = {}; is a special idiom that's used mostly in Perl object programming, and we'll see how it works in some of our methods. (The technical term is that $self is an anonymous hash, if you want to read more about it elsewhere.) Third, we use the bless function. You give this function two parameters: a variable that you want to make into an object, and the type of object you want it to be. This is the line that makes the magic happen! Fourth, we'll set a property called ``_created''. This property isn't really that useful, but it does show the syntax for accessing the contents of an object: $object_name->{property_name}. Finally, now that we've made $self into a new TutorialConfig object, we return it. Our program to create a TutorialConfig object looks like this:

use TutorialConfig; $tut = new TutorialConfig;

(You don't need to use parentheses here, unless your object's new method takes any extra parameters. But if you feel more comfortable writing $tut = new TutorialConfig();, it'll work just as well.) When you run this code, you'll see:
TutorialConfig is successfully loaded! We just created the variable ... and now it's a TutorialConfig object!

Now that we have a class and we can create objects with it, let's make our class do something!

You might also like