Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties?
Perl具有OOP功能,但它们很少使用。如何使用方法和属性创建和使用Perl对象?
8 个解决方案
#1
23
You should definitely take a look at Moose
.
你一定要看看穆斯。
package Point;
use Moose; # automatically turns on strict and warnings
has 'x' => (is => 'rw', isa => 'Int');
has 'y' => (is => 'rw', isa => 'Int');
sub clear {
my $self = shift;
$self->x(0);
$self->y(0);
}
Moose gives you (among other things) a constructor, accessor methods, and type checking for free!
Moose免费提供构造函数,访问器方法和类型检查(除其他外)!
So in your code you can:
所以在你的代码中你可以:
my $p = Point->new({x=>10 , y=>20}); # Free constructor
$p->x(15); # Free setter
print $p->x(); # Free getter
$p->clear();
$p->x(15.5); # FAILS! Free type check.
A good starting point is Moose::Manual
and Moose::Cookbook
一个很好的起点是Moose :: Manual和Moose :: Cookbook
If you just need the basic stuff you can also use Mouse
which is not as complete, but without most of the compile time penalty.
如果你只需要基本的东西,你也可以使用不完整的鼠标,但没有大部分编译时间的惩罚。
#2
8
Moose, definitely.
麋,当然。
package Person;
use Moose;
has age => ( isa => Int, is => 'rw');
has name => ( isa => Str, is => 'rw');
1;
Immediately, you have for free a new() method, and accessor methods for the attributes you just defined with 'has'. So, you can say:
您可以立即免费获得new()方法,以及刚刚使用'has'定义的属性的访问器方法。所以,你可以说:
my $person = Person->new();
$person->age(34);
$person->name('Mike');
print $person->name, "\n";
and so on. Not only that, but your accessor methods come type-checked for free (and you can define your own types as well as the standard ones). Plus you get 'extends' for subclassing, 'with' for roles/traits, and all manner of other great stuff that allows you to get on with the real job of writing good robust maintainable OO code.
等等。不仅如此,您的访问器方法也可以免费进行类型检查(您可以定义自己的类型以及标准类型)。另外,你可以获得子类化的“扩展”,角色/特征的'with',以及各种其他优秀的东西,它们可以让你继续完成编写优秀健壮的可维护OO代码的实际工作。
TMTOWTDI, but this one works.
TMTOWTDI,但这个有效。
#3
5
Currently I use Object::InsideOut whenever I want objects, its quite nice and will give you a lot of features over standard blessed hash objects. Having said that, if I was starting a new project I would seriously look at Moose.
目前,每当我想要对象时,我都会使用Object :: InsideOut,它非常好,并且会比标准的祝福哈希对象提供很多功能。话虽如此,如果我开始一个新项目,我会认真看看穆斯。
While it is good to read the official PERL documentation, I would NOT recommend trying to role your own object framework, or building objects using hashes, its far to tempting to take the easy road and "peak" directly into the objects "private" variables completely breaking encapsulation, this will come back to bite you when you want to refactor the object.
虽然阅读官方PERL文档是好的,但我不建议尝试使用自己的对象框架,或使用哈希构建对象,它很容易采取简单的道路和“峰值”直接进入对象“私有”变量完全打破封装,当你想重构对象时,这会回来咬你。
#4
5
Perl objects are NOT just blessed hashes. They are blessed REFERENCES. They can be (and most often are) blessed hash references, but they could just as easily be blessed scalar or array references.
Perl对象不仅仅是祝福的哈希。他们是幸运的参考。它们可以(并且通常是)受祝福的哈希引用,但它们可以很容易地成为受祝福的标量或数组引用。
#5
3
The official tutorial on the CPAN site is good.
CPAN网站上的官方教程很好。
There's also a good article called Camel POOP at CodeProject.
在CodeProject上还有一篇名为Camel POOP的好文章。
#6
2
I highly recommend taking a look at Moose if you want to do OO in Perl. However, it's not very useful if you don't understand what OO in Perl means. To better understand how Perl OO works under the hood, I wrote an overview on my blog: http://augustinalareina.wordpress.com/2010/06/06/an-introduction-to-object-oriented-perl/
如果你想在Perl中做OO,我强烈建议你看看Moose。但是,如果你不理解Perl中的OO意味着什么,它就没有用。为了更好地理解Perl OO的工作原理,我在我的博客上写了一篇概述:http://augustinalareina.wordpress.com/2010/06/06/an-introduction-to-object-oriented-perl/
From a data structure point of view, an Object is reference with a few extra features. The interpreter knows to treat these special references as Objects because they have been "blessed" with the keyword "bless". Blessed references contain a flag indicating they are an Object. Essentially this means you can define and call methods on them.
从数据结构的角度来看,Object是一个带有一些额外功能的引用。解释器知道将这些特殊引用视为对象,因为它们已经被关键字“bless”“祝福”了。有福的引用包含一个标志,表明它们是一个对象。从本质上讲,这意味着您可以在它们上定义和调用方法。
For instance if you created a basic hashref, this wouldn't work: $hashref->foo();
例如,如果您创建了一个基本的hashref,那么这将不起作用:$ hashref-> foo();
But if you create a blessed hashref (aka an Object) this does work: $blessed_hashref->foo();
但是如果你创建一个有福的hashref(也就是一个Object),这确实有效:$ blessed_hashref-> foo();
Moose is an excellent module for OOP in Perl because it creates an enforceable OO layer AND automagically handles accessor methods so you don't have to define a bunch of getters and setters. If you're interested in using Devel::Peak to see how the Perl interpreter stores objects, follow the link to the blog entry I posted above.
Moose是Perl中OOP的优秀模块,因为它创建了一个可强制执行的OO层并自动处理访问器方法,因此您不必定义一堆getter和setter。如果您有兴趣使用Devel :: Peak查看Perl解释器如何存储对象,请点击上面发布的博客条目链接。
#7
1
On one foot, each class is a package; you establish (multiple, if desired) inheritance by setting the package variable @ISA (preferably at compile time); you create an object from an existing piece of data (often, but not always, an anonymous hash used to store instance variables) with bless(REFERENCE [, CLASSNAME]); you call object methods like $obj->methodname(@ARGS) and class methods like "CLASSNAME"->methodname(@ARGS). Multiple inheritance method resolution order can be altered using mro.
一只脚,每个类都是一个包;通过设置包变量@ISA(最好在编译时)建立(多个,如果需要)继承;你使用bless(REFERENCE [,CLASSNAME])从现有数据(通常但不总是,用于存储实例变量的匿名哈希)创建一个对象;你可以调用像$ obj-> methodname(@ARGS)这样的对象方法和像“CLASSNAME” - > methodname(@ARGS)这样的类方法。可以使用mro更改多重继承方法解析顺序。
Because this is somewhat minimalistic and doesn't force encapsulation, there are many different modules that provide more or different functionality.
因为这有点简约并且不强制封装,所以有许多不同的模块提供更多或不同的功能。
#8
0
Here's a guide: http://www.tutorialspoint.com/perl/perl_oo_perl.htm
这是一本指南:http://www.tutorialspoint.com/perl/perl_oo_perl.htm
Edit: Good point, I'm removing the copied code.
编辑:好点,我正在删除复制的代码。
#1
23
You should definitely take a look at Moose
.
你一定要看看穆斯。
package Point;
use Moose; # automatically turns on strict and warnings
has 'x' => (is => 'rw', isa => 'Int');
has 'y' => (is => 'rw', isa => 'Int');
sub clear {
my $self = shift;
$self->x(0);
$self->y(0);
}
Moose gives you (among other things) a constructor, accessor methods, and type checking for free!
Moose免费提供构造函数,访问器方法和类型检查(除其他外)!
So in your code you can:
所以在你的代码中你可以:
my $p = Point->new({x=>10 , y=>20}); # Free constructor
$p->x(15); # Free setter
print $p->x(); # Free getter
$p->clear();
$p->x(15.5); # FAILS! Free type check.
A good starting point is Moose::Manual
and Moose::Cookbook
一个很好的起点是Moose :: Manual和Moose :: Cookbook
If you just need the basic stuff you can also use Mouse
which is not as complete, but without most of the compile time penalty.
如果你只需要基本的东西,你也可以使用不完整的鼠标,但没有大部分编译时间的惩罚。
#2
8
Moose, definitely.
麋,当然。
package Person;
use Moose;
has age => ( isa => Int, is => 'rw');
has name => ( isa => Str, is => 'rw');
1;
Immediately, you have for free a new() method, and accessor methods for the attributes you just defined with 'has'. So, you can say:
您可以立即免费获得new()方法,以及刚刚使用'has'定义的属性的访问器方法。所以,你可以说:
my $person = Person->new();
$person->age(34);
$person->name('Mike');
print $person->name, "\n";
and so on. Not only that, but your accessor methods come type-checked for free (and you can define your own types as well as the standard ones). Plus you get 'extends' for subclassing, 'with' for roles/traits, and all manner of other great stuff that allows you to get on with the real job of writing good robust maintainable OO code.
等等。不仅如此,您的访问器方法也可以免费进行类型检查(您可以定义自己的类型以及标准类型)。另外,你可以获得子类化的“扩展”,角色/特征的'with',以及各种其他优秀的东西,它们可以让你继续完成编写优秀健壮的可维护OO代码的实际工作。
TMTOWTDI, but this one works.
TMTOWTDI,但这个有效。
#3
5
Currently I use Object::InsideOut whenever I want objects, its quite nice and will give you a lot of features over standard blessed hash objects. Having said that, if I was starting a new project I would seriously look at Moose.
目前,每当我想要对象时,我都会使用Object :: InsideOut,它非常好,并且会比标准的祝福哈希对象提供很多功能。话虽如此,如果我开始一个新项目,我会认真看看穆斯。
While it is good to read the official PERL documentation, I would NOT recommend trying to role your own object framework, or building objects using hashes, its far to tempting to take the easy road and "peak" directly into the objects "private" variables completely breaking encapsulation, this will come back to bite you when you want to refactor the object.
虽然阅读官方PERL文档是好的,但我不建议尝试使用自己的对象框架,或使用哈希构建对象,它很容易采取简单的道路和“峰值”直接进入对象“私有”变量完全打破封装,当你想重构对象时,这会回来咬你。
#4
5
Perl objects are NOT just blessed hashes. They are blessed REFERENCES. They can be (and most often are) blessed hash references, but they could just as easily be blessed scalar or array references.
Perl对象不仅仅是祝福的哈希。他们是幸运的参考。它们可以(并且通常是)受祝福的哈希引用,但它们可以很容易地成为受祝福的标量或数组引用。
#5
3
The official tutorial on the CPAN site is good.
CPAN网站上的官方教程很好。
There's also a good article called Camel POOP at CodeProject.
在CodeProject上还有一篇名为Camel POOP的好文章。
#6
2
I highly recommend taking a look at Moose if you want to do OO in Perl. However, it's not very useful if you don't understand what OO in Perl means. To better understand how Perl OO works under the hood, I wrote an overview on my blog: http://augustinalareina.wordpress.com/2010/06/06/an-introduction-to-object-oriented-perl/
如果你想在Perl中做OO,我强烈建议你看看Moose。但是,如果你不理解Perl中的OO意味着什么,它就没有用。为了更好地理解Perl OO的工作原理,我在我的博客上写了一篇概述:http://augustinalareina.wordpress.com/2010/06/06/an-introduction-to-object-oriented-perl/
From a data structure point of view, an Object is reference with a few extra features. The interpreter knows to treat these special references as Objects because they have been "blessed" with the keyword "bless". Blessed references contain a flag indicating they are an Object. Essentially this means you can define and call methods on them.
从数据结构的角度来看,Object是一个带有一些额外功能的引用。解释器知道将这些特殊引用视为对象,因为它们已经被关键字“bless”“祝福”了。有福的引用包含一个标志,表明它们是一个对象。从本质上讲,这意味着您可以在它们上定义和调用方法。
For instance if you created a basic hashref, this wouldn't work: $hashref->foo();
例如,如果您创建了一个基本的hashref,那么这将不起作用:$ hashref-> foo();
But if you create a blessed hashref (aka an Object) this does work: $blessed_hashref->foo();
但是如果你创建一个有福的hashref(也就是一个Object),这确实有效:$ blessed_hashref-> foo();
Moose is an excellent module for OOP in Perl because it creates an enforceable OO layer AND automagically handles accessor methods so you don't have to define a bunch of getters and setters. If you're interested in using Devel::Peak to see how the Perl interpreter stores objects, follow the link to the blog entry I posted above.
Moose是Perl中OOP的优秀模块,因为它创建了一个可强制执行的OO层并自动处理访问器方法,因此您不必定义一堆getter和setter。如果您有兴趣使用Devel :: Peak查看Perl解释器如何存储对象,请点击上面发布的博客条目链接。
#7
1
On one foot, each class is a package; you establish (multiple, if desired) inheritance by setting the package variable @ISA (preferably at compile time); you create an object from an existing piece of data (often, but not always, an anonymous hash used to store instance variables) with bless(REFERENCE [, CLASSNAME]); you call object methods like $obj->methodname(@ARGS) and class methods like "CLASSNAME"->methodname(@ARGS). Multiple inheritance method resolution order can be altered using mro.
一只脚,每个类都是一个包;通过设置包变量@ISA(最好在编译时)建立(多个,如果需要)继承;你使用bless(REFERENCE [,CLASSNAME])从现有数据(通常但不总是,用于存储实例变量的匿名哈希)创建一个对象;你可以调用像$ obj-> methodname(@ARGS)这样的对象方法和像“CLASSNAME” - > methodname(@ARGS)这样的类方法。可以使用mro更改多重继承方法解析顺序。
Because this is somewhat minimalistic and doesn't force encapsulation, there are many different modules that provide more or different functionality.
因为这有点简约并且不强制封装,所以有许多不同的模块提供更多或不同的功能。
#8
0
Here's a guide: http://www.tutorialspoint.com/perl/perl_oo_perl.htm
这是一本指南:http://www.tutorialspoint.com/perl/perl_oo_perl.htm
Edit: Good point, I'm removing the copied code.
编辑:好点,我正在删除复制的代码。