Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Moo different parameters for constructor

by haukex (Archbishop)
on May 16, 2019 at 11:17 UTC ( [id://11100071]=note: print w/replies, xml ) Need Help??


in reply to Moo different parameters for constructor

(Update: As LanX also said in the meantime,) See the documentation for BUILDARGS in Moo:

use warnings; use strict; package MyDate { use Moo; use Types::Standard qw/ Int /; use Carp; use Date::Calc qw/Today/; use namespace::clean; has year => ( is=>'ro', required=>1, isa=>Int ); has month => ( is=>'ro', required=>1, isa=>Int ); has day => ( is=>'ro', required=>1, isa=>Int ); around BUILDARGS => sub { my ( $orig, $class, %args ) = @_; my %newargs; # NOTE: This does not handle incorrect arguments! if ( keys %args ) { if ( keys %args == 3 ) { %newargs = %args; } elsif ( $args{date} ) { @newargs{qw/year month day/} = $args{date}=~/^(\d{4})(\d\d)(\d\d)$/ or croak "bad date $args{date}"; } } else { my ($year,$month,$day) = Today(); %newargs = (year=>$year, month=>$month, day=>$day); } return $class->$orig(%newargs); }; sub ymd { my $self = shift; return $self->year.'-'.$self->month.'-'.$self->day; } } print "1. ", MyDate->new()->ymd, "\n"; print "2. ", MyDate->new(year=>2019, month=>5, day=>14)->ymd, "\n"; print "3. ", MyDate->new(date=>20190512)->ymd, "\n"; __END__ 1. 2019-5-16 2. 2019-5-14 3. 2019-05-12

Update: To be clear, this is just a template (as requested), since it doesn't really do any checking of the constructor args. Personally, I also like to add use MooX::StrictConstructor; after use namespace::clean; to prevent typos.

Replies are listed 'Best First'.
Re^2: Moo different parameters for constructor
by williamcharles (Novice) on May 16, 2019 at 15:27 UTC
    Thanks for the tip. Also, How can we validate constructor args?
      Also, How can we validate constructor args?

      There's several different ways to do this. The code I showed already uses Type-Tiny, see its documentation on how to use it for tighter constraints, and see the documentation for isa in Moo. I also mentioned MooX::StrictConstructor above.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11100071]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-19 05:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found