1Type::Tie(3) User Contributed Perl Documentation Type::Tie(3)
2
3
4
6 Type::Tie - tie a variable to a type constraint
7
9 Type::Tie is a response to this sort of problem...
10
11 use strict;
12 use warnings;
13
14 {
15 package Local::Testing;
16 use Moose;
17 has numbers => ( is => "ro", isa => "ArrayRef[Num]" );
18 }
19
20 # Nice list of numbers.
21 my @N = ( 1, 2, 3, 3.14159 );
22
23 # Create an object with a reference to that list.
24 my $object = Local::Testing->new(numbers => \@N);
25
26 # Everything OK so far...
27
28 # Now watch this!
29 push @N, "Monkey!";
30 print $object->dump;
31
32 # Houston, we have a problem!
33
34 Just declare @N like this:
35
36 use Type::Tie;
37 use Types::Standard qw( Num );
38
39 ttie my @N, Num, ( 1, 2, 3, 3.14159 );
40
41 Now any attempt to add a non-numeric value to @N will die.
42
44 This module exports a single function: "ttie". "ttie" ties a variable
45 to a type constraint, ensuring that whatever values stored in the
46 variable will conform to the type constraint. If the type constraint
47 has coercions, these will be used if necessary to ensure values
48 assigned to the variable conform.
49
50 use Type::Tie;
51 use Types::Standard qw( Int Num );
52
53 ttie my $count, Int->plus_coercions(Num, 'int $_'), 0;
54
55 $count++; # ok
56 $count = 2; # ok
57 $count = 3.14159; # ok, coerced to 3
58 $count = "Monkey!"; # dies
59
60 While the examples in documentation (and the test suite) show type
61 constraints from Types::Standard, but any type constraint objects
62 supporting the Type::API interfaces should work. This includes:
63
64 · Moose::Meta::TypeConstraint / MooseX::Types
65
66 · Mouse::Meta::TypeConstraint / MouseX::Types
67
68 · Specio
69
70 · Type::Tiny
71
73 Please report any bugs to
74 <http://rt.cpan.org/Dist/Display.html?Queue=Type-Tie>.
75
77 IRC: support is available through in the #moops channel on irc.perl.org
78 <http://www.irc.perl.org/channels.html>.
79
81 Type::API, Type::Utils, Moose::Manual::Types, MooseX::Lexical::Types.
82
84 Toby Inkster <tobyink@cpan.org>.
85
87 This software is copyright (c) 2013-2014, 2018-2019 by Toby Inkster.
88
89 This is free software; you can redistribute it and/or modify it under
90 the same terms as the Perl 5 programming language system itself.
91
93 THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
94 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
95 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
96
97
98
99perl v5.30.1 2020-01-30 Type::Tie(3)