I am writing an OO module and I have some constants that I want to store in a subclass because that module is automatically generated by retrieving some data and printing out the module with the results.
I have searched high and low for the proper OO method for accessing those constants, and I haven't found examples that fit my use case. Here is some simple code that demonstrates what I'm doing:
package Monks; use strict; use warnings; use Monks::Data; BEGIN { use Exporter; our $VERSION = 0.01; our @ISA = qw(Exporter); } sub version { $Monks::VERSION } sub new { my $class = shift; my $self = { @_ }; bless $self, $class; return $self; }; sub check_fluffy { my $self = shift; return 'Yes' if (grep /$_[0]/, @Monks::Data::Fluffy); return 'No'; } sub find_fur_texture { my $self = shift; return "$Monks::Data::Textures{$_[0]}" if (defined $Monks::Data::T +extures{$_[0]}); } 1;
package Monks::Data; use strict; use warnings; use parent 'Monks'; BEGIN { use Exporter (); our $VERSION = 20160808.00; our @ISA = qw(Exporter); } sub version { $Monks::Data::VERSION; } our @Fluffy = qw(Rabbits Minks Cats); our %Textures = ( Rabbits => 'soft', Minks => 'supersoft', Cats => 'coarse', ); 1;
#!/usr/bin/perl use strict; use warnings; use Monks; my $object = Monks->new; for my $animals ( qw(Cats Alligators Rabbits) ) { print "Checking if $animals are furry:\n"; print $object->check_fluffy("$animals"), "\n\n"; } print "Fur texture for Cats: ", $object->find_fur_texture('Cats'), "\n +"; exit 0;
Checking if Cats are furry: Yes Checking if Alligators are furry: No Checking if Rabbits are furry: Yes Fur texture for Cats: coarse
I'm doing this in part as a project to learn more about writing modules, so I don't really want to use a framework like Moose. I've also seen quite a few references to the concept that you should never access data structures directly, that you should always use a method. But I'm not sure that would apply directly in this case. There are also some situations where I need to access the same type of data that is hard-coded into the main module. The common answer for that seems to be to copy that data into the object when it's created, but that seems inefficient in my case because I have some pretty large structures defined to handle a variety of cases where any individual object is only going to need a sliver of that data.
All that said, I'd like to do this right, as I eventually want to publish the module, so I'm open to suggestions.
... and one last thing, thanks to all the monks for all the time and effort you put into your contributions here. I've benefited tremendously over the years.
In reply to OO manner of accessing static variables in a subclass? by HipDeep
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |