Objektorientierte Perl-Konstruktor-syntax, die auch benannte Parameter

Ich bin ein wenig verwirrt über das, was Los ist in Perl Konstruktoren. Ich habe diese beiden Beispiele 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;
}

Und ein weiteres Beispiel ist:

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;
}

Und hier ist das Skript, das verwendet diese Objekte:

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";

Habe ich gespritzt die Fragen/Verwirrung, die habe ich mit in den code als Kommentare.

  • Das ist basic Perl ein, um eine Liste in einen hash. Es wechselt, wobei die erste als Schlüssel und der zweite als Wert. DWIM (do what I mean) ist ein Ziel, das Perl-will-und in der Regel trifft.
  • Da diese Seite ist sehr nützlich, wenn es um das Thema "benannte Parameter" (zusammen mit anderen Dingen) ich habe die phrase in den Titel, damit die Leute es finden können.
InformationsquelleAutor Thomas Owens | 2009-11-09
Schreibe einen Kommentar