gpt4 book ai didi

perl - perl 中的 Hello world OOP 示例?

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

我正在阅读一本 perl 书,但只看过 sub 的函数示例关键词。

是否有定义和使用我自己的类的示例?

如何将下面的PHP重写为perl?

class name {

function meth() {
echo 'Hello World';
}
}

$inst = new name;
$inst->meth();

最佳答案

基本的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;

在你的脚本中:
use Foo;
my $foo = Foo->new(message => "Hello world");
$foo->hello();

不过,您可能更喜欢使用 Moose,在这种情况下,文件 'Foo.pm' 是:
package Foo;
use Moose;
has message => (is => 'rw', isa => 'Str');
sub hello {
my $self = shift;
print $self->message, "\n";
}
1;

因为 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;

关于perl - perl 中的 Hello world OOP 示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6400318/

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