perl - perl 中的 Hello world OOP 示例?

标签 perl

我正在阅读一本 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/

相关文章:

linux - 为什么使用 Perl 的 Device::USB 进行 USB 批量传输会中断?

arrays - Perl中的子程序递归

perl - SSH 与 Perl 使用文件句柄,而不是 Net::SSH

perl - 如何以非 root 用户身份使用 CPAN?

Perl 如何打印八进制字符?

linux - 仅当行号以 + csv 文件开头时才替换行中的单词

perl - 尝试使用 Perl 在树中开发 PostFix 表示法

perl - 如何取消引用从类的方法返回的哈希?

perl - 如何设置 Perl 的 CGI 脚本模块包含路径?

Perl Getopt 多次使用相同的选项