Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 'class'; 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?

like image 212
nicola Avatar asked Apr 04 '11 09:04

nicola


2 Answers

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;
like image 140
FMc Avatar answered Sep 21 '22 04:09

FMc


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.

like image 34
BadFileMagic Avatar answered Sep 22 '22 04:09

BadFileMagic