gpt4 book ai didi

perl - 如何创建 Perl 类?

转载 作者:行者123 更新时间:2023-12-03 12:22:09 25 4
gpt4 key购买 nike

我正在编写 Perl 类以从脚本中删除冗余,并且由于 Perl 有很多方法可以制作类,所以我一直无法正确制作类。那么有没有人有一个类(class)的最佳实践例子?

我最大的问题是模块中是否不应该有全局变量,如何在模块中的 sub() 中使用变量?像 Java self->foo = 10;

基本上只需给我一个用 Java 或 C# 甚至 C++ 编写的类,然后用 Perl 编写相同的类。还展示了如何正确处理私有(private)、 protected 和公共(public)类变量的额外要点。我猜继承和接口(interface)会有所帮助。

最佳答案

嗯,Perl 很简单,但是我对其他语言很生疏,所以我会稍微更新一下。这是一个普通的 Perl 类:

#!/usr/bin/perl

package Person;

use strict;
use warnings;
use Carp;

sub new {
my $class = shift;
my $self = { @_ };
croak "bad arguments" unless defined $self->{firstname} and defined $self->{lastname};
return bless $self, $class; #this is what makes a reference into an object
}

sub name {
my $self = shift;
return "$self->{firstname} $self->{lastname}";
}

#and here is some code that uses it
package main;

my $person = Person->new(firstname => "Chas.", lastname => "Owens");
print $person->name, "\n";

这是使用新的 Moose 样式对象编写的同一个类:
#!/usr/bin/perl

package Person;

use Moose; #does use strict; use warnings; for you

has firstname => ( is => 'rw', isa => 'Str', required => 1 );
has lastname => ( is => 'rw', isa => 'Str', required => 1 );

sub name {
my $self = shift;
return $self->firstname . " " . $self->lastname;
}

#and here is some code that uses it
package main;

my $person = Person->new(firstname => "Chas.", lastname => "Owens");
print $person->name, "\n";

MooseX::Declare 消除了对更多代码的需求,并使事情看起来不错:
#!/usr/bin/perl

use MooseX::Declare;

class Person {
has firstname => ( is => 'rw', isa => 'Str', required => 1 );
has lastname => ( is => 'rw', isa => 'Str', required => 1 );

method name {
return $self->firstname . " " . $self->lastname;
}
}

#and here is some code that uses it
package main;

my $person = Person->new(firstname => "Chas.", lastname => "Owens");
print $person->name, "\n";

快速说明,这两个类是我写过的前两个 Moose 类。这里有一些非常生锈的 C++ 代码(不要在上面割伤自己,否则你需要打破伤风疫苗):
#include <stdio.h>
#include <string.h>

class Person {
char* firstname;
char* lastname;

public:
Person(char* first, char* last) {
firstname = first;
lastname = last;
}

char* name(void) {
int len = strlen(firstname) + strlen(lastname) + 1;
char* name = new char[len];
name[0] = '\0';
strcat(name, firstname);
strcat(name, " ");
strcat(name, lastname);
return name;
}
};

int main(void) {
Person* p = new Person("Chas.", "Owens");
char* name = p->name();
printf("%s\n", name);
delete name;
delete p;
return 0;
}

关于perl - 如何创建 Perl 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1037312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com