1. Perl
  2. Object Oriented
  3. Constructor arguments

Allow arguments to be passed to the constructor

This time, let's make it possible to pass arguments to the constructor.

1. Pass arguments to the constructor.

When creating an object

my $book = Book->new(title =>'Good news', author =>'Kimoto');

Is ideal.

Let's create a constructor with such a function.

sub new {
  my ($class,%args) = @_;
  my $self = {%args};
  return $self, $class;
}

There is nothing particularly difficult.

2. I also want to accept hash reference

You'll want to accept hashes as well as hash reference . Like this.

my $book = Book->new({title =>'Good news', author =>'Kimoto'});

The constructor that can be supported is like this.

sub new {
    my ($class, @args) = @_;
    my %args = ref $args[0] eq 'HASH' ? %{$args[0]} : @args;
    my $self = {%args};
    return $self, $class;
}

If the first argument is a hash reference, dereference it and assign it to the hash. If not, assign the argument as a hash.

3. I want to set a default value in the constructor

Now, the demands on the constructor are still going on. For example, if you want to set a default value when no value is assigned.

sub new {
  my ($class, @args) = @_;
  my %args = ref $args[0] eq 'HASH' ? %{$args[0]} : @args;
  my $self = {%args};
 
  $self->{title} ||='default title';
  $self->{author} ||='default author';

  return $self, $class;
}

Please pay attention to the following part. If the value is a false value, the default value is assigned .

  $self->{title} ||='default title';
  $self->{author} ||='default author';

However, with this, the default value will be set even if an empty string is assigned, so if that is not the case, use the defined function.

  $self->{title} = 'default title' unless defined $self->{title};

will do.

Related Informatrion