perl - 面向对象的 Perl 构造函数语法和命名参数

标签 perl constructor oop instance-variables

我对 Perl 构造函数中发生的事情有点困惑。我找到了这两个例子 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;
}

另一个例子是:
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;
}

这是使用这些对象的脚本:
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";

我已经将我一直在代码中的问题/困惑作为注释注入(inject)了。

最佳答案

您的问题与 OO Perl 无关。您对数据结构感到困惑。

可以使用列表或数组初始化哈希:

my @x = ('High' => 42, 'Low' => 11);
my %h = @x;

use Data::Dumper;
print Dumper \%h;
$VAR1 = {
          'Low' => 11,
          'High' => 42
        };

When you invoke a method on a blessed reference, the reference is prepended to the argument list the method receives:

#!/usr/bin/perl

package My::Mod;

use strict;
use warnings;

use Data::Dumper;
$Data::Dumper::Indent = 0;

sub new { bless [] => shift }

sub frobnicate { Dumper(\@_) }

package main;

use strict;
use warnings;

my $x = My::Mod->new;

# invoke instance method
print $x->frobnicate('High' => 42, 'Low' => 11);

# invoke class method
print My::Mod->frobnicate('High' => 42, 'Low' => 11);

# call sub frobnicate in package My::Mod
print My::Mod::frobnicate('High' => 42, 'Low' => 11);

输出:

$VAR1 = [bless([], 'My::Mod'),'High',42,'Low',11];
$VAR1 = ['My::Mod','High',42,'Low',11];
$VAR1 = ['高',42,'低',11];

关于perl - 面向对象的 Perl 构造函数语法和命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1703046/

相关文章:

arrays - 在有但有一个转折中获得完全匹配

python - SOAP 网络服务 : Python server and perl client

c++ - 对象创建时调用构造函数不明确

unit-testing - Kapt generatetubs - 无法使用单元测试中的内部构造函数初始化对象

c++ - 如何在构造函数中正确初始化wchar_t指针并在析构函数中删除它

perl - Perl嵌套,除非语句不等于&&的使用?

perl - 我可以在构造函数中使用访问器方法吗?

c# - 不同种类的对象初始化

c++ - 使用 Rcpp 公开一个构造函数,该构造函数将指向对象的指针作为参数

java - 枚举是否违反开放/封闭原则 Java?