1. Perl
  2. Object Oriented
  3. accessor

Generate accessor

Let's create an accessor this time.

1. What is an accessor?

You can't directly mess with data in object-oriented programming. This is because in object-oriented programming, it is correct to access objects through exposed methods .

my $book = Book->new;

# No!
$book->{title} = 'aaa';

If you want to mess with the data, do it through the accessor. An accessor is a method for modifying or retrieving data .

The correct way to set a value in the data is to use an accessor as shown below.

my $book = Book->new;
$book->title('aaa');

The creator of the class is obliged to create and publish the accessor.

2. Creating an accessor

Now let's create an accessor. In Perl, it's common to use the same accessor to get and set a value.

(The book Perl Best Plastis says that the accessor for setting and the accessor for getting should be separated, but in practice such as CPAN, it seems that it is preferable to make only one accessor.)

sub title {
  my $self = shift;
  if (@_) {
    $self->{title} = $_[0];
  }
  return $self->{title};
}

The object is in $self. So, if @_ has a value, I set $_[0] to $self->{title}.

The last line returns $self->{title}.

3. If a value is set, create an accessor that returns the old value

In addition to the above accessors, it is also common to implement an accessor that returns the old value when a value is set.

my $book = Book->new(title =>'aaa');
my $old_val = $book->title('bbb');

Create an accessor that returns the old value as follows:

sub title {
  my $self = shift;
  if (@_) {
    my $old = $self->{title};
    $self->{title} = $_[0];
    return $old;
  }
  else {
    return $self->{title};
  }
}

This concludes the discussion of constructors and accessors. All you have to do now is add your favorite methods.

Related Informatrion