Perl使用'new'中声明的变量

Bri*_*n H 1 variables perl

如果在Perl模块中我有一个'new'函数声明:

 my $self = $class->SUPER::new($pArgsProcessor, $pResponse, kStrFormatHtml);
 $self->{mStrRunType} = $pArgsProcessor->readQueryString('runType');
 $self->{mStrStartDate} = $pArgsProcessor->readQueryString('startdate');
 $self->{mStrEndDate} = $pArgsProcessor->readQueryString('enddate');
 bless $self, $class;
 return $self;
Run Code Online (Sandbox Code Playgroud)

有没有办法在另一个函数中使用'$ self'中存储的数据?我正在尝试使用'mStrRunType'

amo*_*mon 5

$self可能是一个对象,包中的所有subs都可以作为方法调用.然后:

my $object = Your::Class->new(...);

$object->foo(42);
Run Code Online (Sandbox Code Playgroud)

在foo方法内部,对象将是第一个参数:

sub foo {
  my ($self, $meaning_of_life) = @_;
  say "mStrEndDate = $self->{mStrEndDate}";
  ...;
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 你通常不应该$self在你的构造函数中重新使用它.如果编写超类来支持继承,那么$class->SUPER::new(...)确保将引用保存为正确的$class.
  • 您的命名方案表明您可能希望使用更复杂的数据结构:

    $self->{mStr} = {
      RunType   => ...,
      StartDate => ...,
      EndDate   => ...,
    };
    
    Run Code Online (Sandbox Code Playgroud)