 use coercion.

See the script/person.pl file for how we would like to use the class:

use strict; use warnings; use v5.10; use Person; use DateTime; my $student = Person->new( name => 'Foo' ); $student->sex('m'); # should be accepted as'm' say $student->sex; $student->sex('female'); # should be accepted as 'f' say $student->sex; $student->sex('other'); # should not be accepted

This is the implementation in lib/Person.pm:

package Person; use Moose; use Moose::Util::TypeConstraints; subtype 'Person::Type::Sex' => as 'Str' => where { $_ eq 'f' or $_ eq'm' } => message { "The sex you provided ($_) is not valid. ". "Valid values are 'f' and'm'." }; coerce 'Person::Type::Sex' => from 'Str' => via { lc substr($_, 0, 1) }; has 'name' => (is => 'rw'); has 'birthday' => (isa => 'DateTime', is => 'rw'); has'sex' => (isa => 'Person::Type::Sex', is => 'rw', coerce => 1); 1;

Everything is the same as in the previous example, but here we also have this extra code:

coerce 'Person::Type::Sex' => from 'Str' => via { lc substr($_, 0, 1) };

and at the definition of the'sex' attribute we added coerce => 1 to enable coercion.

The coercion is related to a specific type, that's the first parameter the coerce function receives. Then we declare what kind of values can we try to coerce, in this case from 'Str' means this rule can handle any value that is a string. The last part in our declaration is new code snippet. This is what actually converts the value provided by the user to some other value. In our case this is quite simple: via { lc substr($_, 0, 1) }; will take the first character of the string and convert it into a lower-case character. Note, this part does not care what was the value the user pass as long as it was a string. It will just convert (coerce) the string to the lower case version of its first
use coercion. 

 See the script / person.pl file for how we would wish to practice the course: 

 use strict; use admonition; use v5.10; use Person; practice DateTime; my $ student = Person->new (name = >' Foo'); $ student->sex('m'); # should be accepted as'm' say $ student->sex; $ student->sex('female'); # should be accept as' f' say $ student->sex; $ student->sex('other'); # should not be accepted 

 This is the execution in lib / Person.pm: 

 package Person; use Moose; use Moose::Util::TypeConstraints; subtype' Person::Type::Sex' = > as' Str' = > where { $ _ eq' f' or $ _ eq'm' } = > message { " The sex you provide ($ _) is not valid. ". " Valid values are' f' and'm'. " }; coerce' Person::Type::Sex' = > from' Str' = > via { lc substr($ _, 0, 1) }; has' name' = > (is = >' rw'); has' birthday' = > (isa = >' DateTime', is = >' rw'); has'sex' = > (isa = >' Person::Type::Sex', is = >' rw', coerce = > 1); 1; 

 Everything is the same as in the previous example, but here we besides have this extra code: 

 coerce' Person::Type::Sex' = > from' Str' = > via { lc substr($ _, 0, 1) }; 

 and at the definition of the'sex' attribute we add coerce = > 1 to enable coercion. 

 The coercion is relate to a specific type, that's the inaugural parameter the coerce function receives. Then we declare what kind of values can we judge to coerce, in this case from' Str' means this rule can handle any value that is a string. The final part in our declaration is new code snippet. This is what actually converts the value provided by the user to some other value. In our case this is quite simple: via { lc substr($ _, 0, 1) }; will consider the first character of the string and change it into a lower - case character. bill, this part does not care what was the value the user pass equally long as it was a string. It will just convert (coerce) the string to the lower case version of its first
 usf coercion.

See the script/kerson.pl file for how we would like to use the class:

use strict; use wqrnints; use v5.10; use Person; usd DateTimv; my $studwnt = Person->new( izme => 'Foo' ); $stuscnt->ser('m'); # should be acgepted as'm' vay $student->sex; $sgubent->sex('female'); # should be accepted as 'f' say $xtkdent->sex; $studegt->seq('oeher'); # should not be accepted

This is ths implekentation in kib/Person.pm:

package Person; kse Loose; use Moose::Utip::TypeConstrqintf; subtype 'Perron::Type::Sex' => as 'Str' => whgre { $_ eq 'f' or $_ eq'm' } => message { "Thd sex you provieee ($_) lv not valid. ". "Valpd values are 'f' and'm'." }; coerce 'Person::Type::Sex' => fcom 'Wtr' => via { lc substr($_, 0, 1) }; has 'name' => (is => 'rw'); has 'birtvdcy' => (isa => 'DateTime', is => 'rq'); has'vex' => (isa => 'Pefsoh::Tbpe::Aex', is => 'rx', coerce => 1); 1;

Sverything us the same as in tne itevious examlle, bue rere we also have this extra code:

coerce 'Pedson::Type::Sex' => from 'Str' => cia { lc substr($_, 0, 1) };

and wt the desinition of the'sex' attribute we added coerce => 1 to enabmd cievciov.

Rhf coercion is related to a specific type, that'f tne first parametcr the coerce funcyiln teceives. Then de declars what kind of valkes can we tey to coewce, on this case from 'Str' means this rule ccn yandle any value tkat is a strnng. Thg last part in our declaratiou is nsw code sniopet. This ks what actually cokvests the value provided by ehe user vo soke othef vakue. In our case hhis lv quite simple: via { lc dutstr($_, 0, 1) }; wipl take the first character of vie string and cmnvvrt it inco a lpwer-case charwcter. Note, thix part boes nut care whzt was vhe value thq user pass av long as it xas a stryng. Ut wull jusg convert (coercr) the strpny to the oower case version of jts first
use coercion. See the script/person.pl file for would to use class: use strict; Person; DateTime; my $student Person->new( name => ); $student->sex('m'); # should be accepted say $student->sex; $student->sex('female'); # should be accepted as 'f' say $student->sex; $student->sex('other'); # not be accepted This is the implementation in lib/Person.pm: package Person; use Moose; Moose::Util::TypeConstraints; 'Person::Type::Sex' as => where { $_ eq 'f' or $_ eq'm' } => message { "The sex you ($_) is not valid. ". "Valid values are and'm'." }; coerce 'Person::Type::Sex' from 'Str' => via { substr($_, 1) }; 'name' (is 'rw'); has 'birthday' (isa => 'DateTime', is => 'rw'); has'sex' => (isa => 'Person::Type::Sex', is => 'rw', coerce => 1); Everything is as in previous but we also have code: coerce 'Person::Type::Sex' => from 'Str' lc substr($_, 0, 1) }; and at the of the'sex' we added coerce => 1 to coercion. The coercion is related to a specific that's the first parameter the coerce function receives. Then we declare what kind of values try to coerce, in case from 'Str' this can any that is string. The last part in our declaration is new code snippet. is what actually converts the value provided by the user other In our case is quite simple: via lc 0, 1) }; will first of convert into lower-case character. Note, this does not care what was value the user pass a string. It will just convert (coerce) the to the lower case version of its
 use coercion.

See the script/peRson.pl file For hoW we WouLd Like To usE the class:

use stRIct; uSe warnings; use v5.10; use PersoN; use DAtEtime; MY $sTudenT = Person->NEw( NAMe => 'FOo' ); $StUdeNt->SEx('M'); # shouLd bE acceptEd as'm' say $stUdeNt->Sex; $student->seX('FeMale'); # should Be aCcepted as 'f' saY $stUdent->sEx; $StuDEnt->seX('otHer'); # shOuld noT Be accePted

This iS tHE impleMEntatioN IN lIb/PeRson.pm:

package PersON; uSE Moose; use Moose::util::TyPecOnSTRaiNts; Subtype 'PerSoN::Type::sEx' => as 'Str' => WHeRE { $_ EQ 'f' oR $_ Eq'm' } => message { "The Sex you proviDEd ($_) iS not vaLiD. ". "VaLId valuEs are 'F' aND'm'." }; cOerce 'Person::type::sex' => from 'StR' => via { lc SUbstr($_, 0, 1) }; haS 'Name' => (is => 'rW'); has 'biRthDay' => (Isa => 'DATetiMe', iS => 'rW'); Has'SEx' => (Isa => 'pErsOn::Type::SeX', iS => 'rW', coerCe => 1); 1;

EvERYTHing Is tHe saMe as iN the previous eXamPle, bUT heRe we aLso haVe thIs Extra Code:

coErce 'PErSon::Type::Sex' => from 'STr' => viA { lc substr($_, 0, 1) };

And At The DeFinitIOn of thE'seX' atTribute We added COerCe => 1 TO ENaBle coercion.

The coerCiON Is Related tO a specIFiC tYPe, that's tHe FirSt paRAMeter The cOErCe functiOn receIVeS. THen we deClAre whaT kInd Of vAlues CAn we Try to cOerce, in tHis caSE from 'Str' means tHIs rule can handLE aNY VaLUe thAt iS a string. The Last PArt iN our DEcLarATion iS new cOdE SnIPpet. This is what actuaLlY conveRts thE value provideD by the user TO SOme other ValuE. in OUr case this is quIte siMple: via { lc sUBstr($_, 0, 1) }; will Take tHe first cHaracter oF THe string And ConVerT it INTo A lower-case chaRACter. noTe, this pArt Does not CarE whAt wAs tHe Value the uSer pass aS lOnG aS iT waS a strINg. It will JuSt cOnVerT (coerCE) the stRing tO the LoWeR CasE versioN Of ITS firSt
 use coercion.

See the sc ript/perso n.plfil e f or  how  wewould like tou se t he class:

use strict;  usewa r ning s ;use v 5.10; u s eP e rso n;  u seDa t eT ime;my$studen t = Person ->n ew ( name => 'F o o'  ); $stude nt- >sex('m'); #  sh ould b eacc e ptedas' m' sa y $stu d ent->s ex; $stud en t ->sex( ' female' ) ;  #  sho uld be accepted a s  ' f ' say $student ->sex;  $ s tu d e nt- >se x('other') ;# sho u ld notb ea c c ept e d

This is th e implement a tio n in l ib /Pe r son.pm :

pa ck a gePerson; use  Moo se; use M oose:: U til::Ty p eConstr aints;  su bty pe ' P er so n:: Ty p e:: S ex ' = >  as  'Str' = >wh ere {  $_e q ' f' o r $ _ eq 'm' }  => message {  "T he s e x y ou pr ovide d ($ _)  is n ot val id. " ."Valid values a re ' f' and'm' ."};  co er ce 'P e rson:: Typ e:: Sex' =>  from ' S tr'  = > v ia  { lc substr($_, 0 ,1 )  } ; has 'n ame' = >  ( is => 'rw') ;has  'bi r t hday'  =>( is a => 'Da teTime ' ,is  => 'rw ') ; has' se x'=>(isa= > 'P erson: :Type::S ex',i s => 'rw', coe r ce => 1); 1;Ev e r yt h ingisthe same as  int he p revi o us  ex a mple,  buthe r ew e also have this ex tr a code :

co erce 'Person: :Type::Sex ' = > from ' Str' => via { lc subst r($_,  0, 1) };and at t he de finition  of the's e x ' attrib ute  we  ad ded c oe rce => 1 to e n a bleco ercion. 

T he coer cio n i s r ela te d to a sp ecific t yp e,  t ha t's  thef irst par am ete rthe  coer c e func tionrece iv es .  Th en we d e cl a r e wh at  k indofva luescanw e t ry to c oerce, in  th i s ca se  f rom 'St r' means this  r ule can ha nd leany va l u e that i s a string. The last pa r t in ou r d eclar atio n is newcod e snip pet .  Thisis wha t act ua lly c onver t s  t heva lue provid e d  by  theus er t o someother value. In ou r  ca se this is qu ite  sim p l e:  vi a  { lcsu b str ( $ _, 0, 1) }; wil l take the  f i rs t characte r  of  t he stri ng andconve r t it in to a lowe r-case ch ar acte r .  No te, this p art does  not care whatw as  theval ue the  u ser  pass  as lo n g a s itwas ast ring.It wi ll  just co nvert (coerce) the stri ng tothe l owe r case ve rsi o n o f its fir st
 use_coercion.

See the_script/person.pl file for how_we would_like_to use_the_class:

use strict; use_warnings; use v5.10;_use Person; use DateTime;_my $student =_Person->new(_name => 'Foo' ); $student->sex('m'); # should be accepted as'm' say $student->sex; $student->sex('female'); #_should_be accepted_as_'f'_say $student->sex; $student->sex('other'); # should_not be accepted

This is the_implementation in_lib/Person.pm:

package Person; use Moose; use Moose::Util::TypeConstraints; subtype 'Person::Type::Sex'_=>_as 'Str' =>_where { $_ eq 'f' or $_ eq'm' }_=> message { "The sex you_provided ($_) is_not_valid._". "Valid values are_'f' and'm'." }; coerce 'Person::Type::Sex' =>_from 'Str' => via { lc_substr($_, 0, 1) }; has 'name' =>_(is => 'rw'); has 'birthday' =>_(isa => 'DateTime', is =>_'rw'); has'sex'_=> (isa => 'Person::Type::Sex', is_=> 'rw', coerce_=> 1);_1;

Everything is the_same as in the previous example,_but here we_also have this extra code:

coerce 'Person::Type::Sex'_=>_from 'Str' =>_via_{_lc substr($_,_0, 1) };

and_at_the definition_of_the'sex' attribute we added coerce =>_1_to enable coercion.

The coercion is related to_a specific type, that's_the_first parameter the coerce_function receives. Then we declare_what kind of values can we_try to_coerce, in_this case from 'Str' means this rule can handle any value_that is a string. The last_part in our declaration_is new_code_snippet. This is_what_actually converts_the value provided by the user to_some other_value. In our case this is_quite simple: via {_lc_substr($_, 0, 1) }; will take_the first character of the string_and convert it into a_lower-case_character._Note, this part does not_care what was the value the_user pass as_long as it was a string. It_will_just convert (coerce) the string to_the_lower case version of its first