开发者

Perl static class properties

As I know, creating dynamic instances of a class (package) is like a hack on Perl syntax (using 'bless'). Perl doesn't support a keyword called 'cla开发者_开发知识库ss'; thus everything is limited.

The first limitation of Perl which causes difficulty in OOP is when creating static class properties and static class methods. Any solution?


For class-level variables there are two commonly used approaches:

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;

Example usage:

use Bar;

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


In this day and age, if you really want to do OOP with Perl, you'd be well advised to use an object framework like Moose that will help clean up the crufty syntax. It will make doing OO in Perl hurt a lot less, and if you use extensions like MooseX::Declare, it'll be even sweeter.

I don't do a whole lot of OO stuff, but I think I know what you're trying to do, and I do believe Moose can make it straight forward to do so.


I've found a solution:

package test;

my $static_var = undef;

#constructor not needed

#static method to set variable
sub set_var {
    my ($value) = @_;
    $static_var = $value;
}

#static method to get variable value
sub get_var {
    return $static_var;
}

1;

According to http://www.stonehenge.com/merlyn/UnixReview/col46.html, it doesn't seem possible to access those variables in package directly. Maybe there must be get, set methods to access them.

As said in the above article:

There's also no syntax that would let any other code outside of this code access those variables, so we can be assured that our variables won't be changing mysteriously.

I don't really know whether that author is right.


A standard package variable behaves as a class variable

package foo;

my $bar;

1;

then:

$foo::bar=1;  # or whatever
$foo::bar++;
print $foo::bar, "\n";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜