Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Type::Coercion on the fly

by jandrew (Chaplain)
on Jul 08, 2014 at 15:09 UTC ( [id://1092740]=perlquestion: print w/replies, xml ) Need Help??

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

Hello all,

I have one of those questions where the possible answer may be don't do that. However, I am attempting to build Type::Coercion objects/instances on the fly and I am having some trouble figuring out what I'm doing wrong.

I would like the code below;
#! perl use strict; use warnings; use Type::Utils -all; use Type::Library -base, -declare => qw( IncreaseMagnetude ); use Types::Standard qw( Num Str ); use Type::Coercion; my $lookup ={ Ten => 10 }; declare_coercion IncreaseMagnetude, to_type Num, from Str, via{ $lookup->{$_} * 10 }; # Alternate on-the-fly version my $more_magnetude = Type::Coercion->new( name => 'MoreMagnitude', to_type => Num, from => Str, via => sub{ $lookup->{$_}* 11 }, ); print "Using: " . IncreaseMagnetude->display_name . " -> "; print IncreaseMagnetude->( 'Ten' ) . "\n"; print "Using: " . $more_magnetude->display_name . " -> "; print $more_magnetude->( 'Ten' ) . "\n";
to print out the following;
Using: IncreaseMagnetude -> 100 Using: MoreMagnitude -> 110
but instead I get;
Using: IncreaseMagnetude -> 100 Using: MoreMagnitude -> Ten

Replies are listed 'Best First'.
Re: Type::Coercion on the fly
by tobyink (Canon) on Jul 08, 2014 at 15:36 UTC

      tobyink++

      That was both fast and helpful! Thanks for the solution and the pointer to the documentation.

      Update: I'm looking forward to the book!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-25 10:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found