Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

pre-preprocess Moose args in constructor

by Anonymous Monk
on Apr 14, 2018 at 06:21 UTC ( #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 (Pilgrim) 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?

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2018-08-22 05:40 GMT
Find Nodes?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:

    Results (204 votes). Check out past polls.