1. Perl
  2. Object Oriented
  3. Create constructor

Creating a constructor

Last time, I created the following class template.

package Book;

sub new {# Constructor implementation}

sub title {# Implementation of accessor}
sub author {# Implementation of accessor}

1. What is a constructor?

Objects are created based on the class . Forget a little about what an object is and what a class is, and remember that "objects are created from a class".

And a constructor is a method that creates an object. If you create a constructor

my $book = Book->new;

You will be able to create an object with the description.

The name new is customarily used for the constructor name. But be sure to name the constructor new(because those who use your module expect the constructor name to be new)

2. Implementation of the simplest constructor

Now let's implement the constructor. Below is the simplest constructor implementation. But the easiest is a little difficult.

sub new {
    my $class = shift;
    my $self = {};
    return bless $self, $class;
}

Call the following

my $book = Book->new;

What will be assigned to $class when you do?

The answer is Book . The constructor new takes a class name as the first argument.

3. Prepare a hash reference

  my $self = {};

What is the line doing?

This is actually object-owned data . It's important, so I'll say it again. The object owns the data . And, in general, the hash reference is selected as the data.

(To tell the truth, the object is the data itself. Remember that the object owns the data at first so it doesn't get confusing.)

4. Connect data to class

Last line

return bless $self, $class;

Has a function called bless.

The bless function takes data in the first argument and the class name in the second argument, and connects the data and the class.

Objects are created by connecting data and classes . Then, I will return the tied one to the caller.

5. What are objects in Perl?

A Perl object is the data associated with a class . It doesn't mean anything more or less.

And the objects created in this way perform as well as the objects used in other languages.

Related Informatrion