in reply to Is there a better way to do this?
Hi TorontoJim,
I would compose in my methods with roles. I use Moo and Moo::Role:
In MyClass.pm -
In MyClass/Child.pm -package MyClass; use Moo; with 'MyClass::Child'; sub foo { return 'foo'; } 1;
In your script:package MyClass::Child; use Moo::Role; sub foo { die 'horribly'; } sub bar { return 'bar'; } 1;
Output:#!/usr/bin/perl use strict; use warnings; use feature 'say'; use MyClass; my $obj = MyClass->new; say $obj->foo; say $obj->bar; __END__
$ perl 1158279.pl foo bar
You could also use Role::Tiny directly, but with Moo you'll of course get access to the other sugar like not having to write a constructor, type-checking, etc.
If you have a whole bunch of roles and for some reason they are expensive to compile you can load them conditionally with with and eval, say based on arguments passed to the constructor call:
package MyClass; use Moo; sub BUILD { my ( $self, $args ) = @_; my %modules = ( 1 => 'MyClass::MyChild', 0 => 'Acme::Frobnicate', ); my $module = $modules{ $args->{'be_serious'} }; eval "with '$module'; 1;" or die $@; return $self; } sub foo { return 'foo'; } 1;
As far as whether you should be rethinking what you're doing, there's certainly no harm in reinventing a wheel as an academic exercise ... but I would look at the DateTime project (maybe especially DateTime.pm#How_DateTime_Math_Works), Date::Calc, even Time::Piece before I put too many CPU cycles into tackling date math. I'd also recommend against releasing any code under the Date::Math namespace, until you're very sure that it's at least as reliable as the aforementioned modules.
Hope this helps!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Is there a better way to do this?
by choroba (Cardinal) on Mar 19, 2016 at 09:46 UTC | |
by 1nickt (Canon) on Mar 19, 2016 at 16:35 UTC | |
by choroba (Cardinal) on Mar 19, 2016 at 17:40 UTC | |
by 1nickt (Canon) on Mar 19, 2016 at 18:31 UTC | |
by choroba (Cardinal) on Mar 19, 2016 at 18:45 UTC | |
| |
by Your Mother (Archbishop) on Apr 09, 2019 at 02:43 UTC | |
|
Re^2: Is there a better way to do this?
by TorontoJim (Beadle) on Mar 19, 2016 at 14:04 UTC |