Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

pre-preprocess Moose args in constructor

by Anonymous Monk
on Apr 14, 2018 at 06:21 UTC ( [id://1212851]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Esteemed and hallowed Monks: Trying to force upper case on Moose args taken from command line - eg FX currency codes - e.g.
$lookup usd eur gbp chf
Yes - I could put it into the calling code - but how would I get Moose to force it itself - I tried this from Moose docs:
trigger => sub { $_[0]->code( uc( $_[0]->code ) );
but I get message that I am unable to to modify read-only value despite Moose docs saying that trigger can modify RO values. What is correct way to force upper case (and thus in general) 'pre-preocess' object constructor arguments? Thank-you.

Replies are listed 'Best First'.
Re: pre-preprocess Moose args in constructor
by haj (Vicar) on Apr 14, 2018 at 09:28 UTC
    There are several ways to do this, depending on how much validation you want to add. A lightweight method without any validation is to add a BUILDARGS routine to your class (see Moose::Manual::Construction):
    sub BUILDARGS { my $class = shift; my %args = ref $_[0] ? %{$_[0]} : @_; $args{code} = uc $args{code} if exists $args{code}; return \%args; }
    A more idiomatic method is to add a Moose type for the currency code, check for its validity, and then allow lowercase input by converting it under the hood by Moose coercion. Here's a complete example: BTW: I don't think that triggers are supposed to be allowed to change readonly attributes. Where did you read that?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1212851]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-04-24 07:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found