Object-Oriented Perl constructor syntax and named

2020-02-02 06:13发布

I'm a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot.

package Foo;

#In Perl, the constructor is just a subroutine called new.
sub new {
  #I don't get what this line does at all, but I always see it. Do I need it?
  my $type = shift;

  #I'm turning the array of inputs into a hash, called parameters.
  my %params = @_;

  #I'm making a new hash called $self to store my instance variables?
  my $self = {};

  #I'm adding two values to the instance variables called "High" and "Low".
  #But I'm not sure how $params{'High'} has any meaning, since it was an
  #array, and I turned it into a hash.
  $self->{'High'} = $params{'High'};
  $self->{'Low'} = $params{'Low'};

  #Even though I read the page on [bless][2], I still don't get what it does.
  bless $self, $type;
}

And another example is:

package Bar;

sub new {
  my $type = shift;

  #I still don't see how I can just turn an array into a hash and expect things
  #to work out for me.
  my %params = @_;
  my $self = [];

  #Exactly where did params{'Left'} and params{'Right'} come from?
  $self->[0] = $params{'Left'};
  $self->[1] = $params{'Right'};

  #and again with the bless.
  bless $self, $type;
}

And here is the script that uses these objects:

package main;

$a = Foo->new( 'High' => 42, 'Low' => 11 );
print "High=$a->{'High'}\n";
print "Low=$a->{'Low'}\n";

$b = Bar->new( 'Left' => 78, 'Right' => 40 );
print "Left=$b->[0]\n";
print "Right=$b->[1]\n";

I've injected the questions/confusion that I've been having into the code as comments.

7条回答
虎瘦雄心在
2楼-- · 2020-02-02 07:17

In Perl, all arguments to subroutines are passed via the predefined array @_.

The shift removes and returns the first item from the @_ array. In Perl OO, this is the method invocant -- typically a class name for constructors and an object for other methods.

Hashes flatten to and can be initialized by lists. It's a common trick to emulate named arguments to subroutines. e.g.

Employee->new(name => 'Fred Flintstone', occupation => 'quarry worker');

Ignoring the class name (which is shifted off) the odd elements become hash keys and the even elements become the corresponding values.

The my $self = {} creates a new hash reference to hold the instance data. The bless function is what turns the normal hash reference $self into an object. All it does is add some metadata that identifies the reference as belonging to the class.

查看更多
登录 后发表回答