Perl静态类属性

nic*_*ola 10 oop syntax perl static class

据我所知,创建类(包)的动态实例就像是对Perl语法的破解(使用'bless').Perl不支持名为"class"的关键字; 因此一切都是有限的.

在创建静态类属性静态类方法时,导致OOP困难的Perl的第一个限制.有解决方案吗

FMc*_*FMc 17

对于类级变量,有两种常用方法:

package Bar;
use strict;
use warnings;

sub new { bless {}, shift };

# (1) Use a lexical variable scoped at the file level,
# and provide access via a method.
my $foo = 123;
sub get_foo { $foo }

# (2) Use a package variable. Users will be able to get access via
# the fully qualified name ($Bar::fubb) or by importing the name (if
# your class exports it).
our $fubb = 456;
Run Code Online (Sandbox Code Playgroud)

用法示例:

use Bar;

my $b = Bar->new;
print "$_\n" for $b->get_foo(), $Bar::fubb;
Run Code Online (Sandbox Code Playgroud)


小智 7

在这个时代,如果你真的想用Perl做OOP,你最好使用像Moose这样的对象框架来帮助清理狡猾的语法.它会使Perl中的OO伤害更少,如果你使用像MooseX :: Declare这样的扩展,它会更甜蜜.

我没有做很多OO的事情,但我想我知道你要做什么,而且我确实相信Moose可以直截了当地做到这一点.