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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With