我正在读一本perl书,但只看过sub关键字的函数示例.
有定义和使用我自己的类的例子吗?
如何将下面的PHP重写为perl?
class name {
function meth() {
echo 'Hello World';
}
}
$inst = new name;
$inst->meth();
Run Code Online (Sandbox Code Playgroud)
Ale*_*lex 14
basic-perl方式是:
在'Foo.pm'文件中:
use strict;
use warnings;
package Foo;
sub new {
my $class = shift;
my $self = bless {}, $class;
my %args = @_;
$self->{_message} = $args{message};
# do something with arguments to new()
return $self;
}
sub message {
my $self = shift;
return $self->{_message};
}
sub hello {
my $self = shift;
print $self->message(), "\n";
}
1;
Run Code Online (Sandbox Code Playgroud)
在你的脚本中:
use Foo;
my $foo = Foo->new(message => "Hello world");
$foo->hello();
Run Code Online (Sandbox Code Playgroud)
你可能更喜欢使用Moose,在这种情况下文件'Foo.pm'是:
package Foo;
use Moose;
has message => (is => 'rw', isa => 'Str');
sub hello {
my $self = shift;
print $self->message, "\n";
}
1;
Run Code Online (Sandbox Code Playgroud)
因为Moose为您制作了所有的访问器.你的主文件是完全一样的......
或者你可以使用Moose扩展来使一切变得更漂亮,在这种情况下,Foo.pm变为:
package Foo;
use Moose;
use MooseX::Method::Signatures;
has message => (is => 'rw', isa => 'Str');
method hello() {
print $self->message, "\n";
}
1;
Run Code Online (Sandbox Code Playgroud)
Modern Perl是一本优秀的书,免费提供,其中有关于使用Moose编写OO Perl的详尽部分.(从PDF版本的第110页开始.)
我将从perlboot手册页开始.
从那里你可以继续perltoot,perltooc和perlbot ......
我发现这是一个更简约的版本:
package HelloWorld;
sub new
{
my $class = shift;
my $self = { };
bless $self, $class;
return $self;
}
sub print
{
print "Hello World!\n";
}
package main;
$hw = HelloWorld->new();
$hw->print();
Run Code Online (Sandbox Code Playgroud)
对于任何希望使用这个进一步分叉的人来说,请访问https://gist.github.com/1033749