1Types::Standard(3) User Contributed Perl Documentation Types::Standard(3)
2
3
4
6 Types::Standard - bundled set of built-in types for Type::Tiny
7
9 This module is covered by the Type-Tiny stability policy.
10
12 Type::Tiny bundles a few types which seem to be useful.
13
14 Moose-like
15 The following types are similar to those described in
16 Moose::Util::TypeConstraints.
17
18 "Any"
19 Absolutely any value passes this type constraint (even undef).
20
21 "Item"
22 Essentially the same as "Any". All other type constraints in this
23 library inherit directly or indirectly from "Item".
24
25 "Bool"
26 Values that are reasonable booleans. Accepts 1, 0, the empty string
27 and undef.
28
29 "Maybe[`a]"
30 Given another type constraint, also accepts undef. For example,
31 "Maybe[Int]" accepts all integers plus undef.
32
33 "Undef"
34 Only undef passes this type constraint.
35
36 "Defined"
37 Only undef fails this type constraint.
38
39 "Value"
40 Any defined, non-reference value.
41
42 "Str"
43 Any string.
44
45 (The only difference between "Value" and "Str" is that the former
46 accepts typeglobs and vstrings.)
47
48 Other customers also bought: "StringLike" from Types::TypeTiny.
49
50 "Num"
51 See "LaxNum" and "StrictNum" below.
52
53 "Int"
54 An integer; that is a string of digits 0 to 9, optionally prefixed
55 with a hyphen-minus character.
56
57 "ClassName"
58 The name of a loaded package. The package must have @ISA or
59 $VERSION defined, or must define at least one sub to be considered
60 a loaded package.
61
62 "RoleName"
63 Like "ClassName", but the package must not define a method called
64 "new". This is subtly different from Moose's type constraint of the
65 same name; let me know if this causes you any problems. (I can't
66 promise I'll change anything though.)
67
68 "Ref[`a]"
69 Any defined reference value, including blessed objects.
70
71 Unlike Moose, "Ref" is a parameterized type, allowing
72 Scalar::Util::reftype checks, a la
73
74 Ref["HASH"] # hashrefs, including blessed hashrefs
75
76 "ScalarRef[`a]"
77 A value where "ref($value) eq "SCALAR" or ref($value) eq "REF"".
78
79 If parameterized, the referred value must pass the additional
80 constraint. For example, "ScalarRef[Int]" must be a reference to a
81 scalar which holds an integer value.
82
83 "ArrayRef[`a]"
84 A value where "ref($value) eq "ARRAY"".
85
86 If parameterized, the elements of the array must pass the
87 additional constraint. For example, "ArrayRef[Num]" must be a
88 reference to an array of numbers.
89
90 Other customers also bought: "ArrayLike" from Types::TypeTiny.
91
92 "HashRef[`a]"
93 A value where "ref($value) eq "HASH"".
94
95 If parameterized, the values of the hash must pass the additional
96 constraint. For example, "HashRef[Num]" must be a reference to an
97 hash where the values are numbers. The hash keys are not
98 constrained, but Perl limits them to strings; see "Map" below if
99 you need to further constrain the hash values.
100
101 Other customers also bought: "HashLike" from Types::TypeTiny.
102
103 "CodeRef"
104 A value where "ref($value) eq "CODE"".
105
106 Other customers also bought: "CodeLike" from Types::TypeTiny.
107
108 "RegexpRef"
109 A reference where "re::is_regexp($value)" is true, or a blessed
110 reference where "$value->isa("Regexp")" is true.
111
112 "GlobRef"
113 A value where "ref($value) eq "GLOB"".
114
115 "FileHandle"
116 A file handle.
117
118 "Object"
119 A blessed object.
120
121 (This also accepts regexp refs.)
122
123 Structured
124 OK, so I stole some ideas from MooseX::Types::Structured.
125
126 "Map[`k, `v]"
127 Similar to "HashRef" but parameterized with type constraints for
128 both the key and value. The constraint for keys would typically be
129 a subtype of "Str".
130
131 "Tuple[...]"
132 Subtype of "ArrayRef", accepting a list of type constraints for
133 each slot in the array.
134
135 "Tuple[Int, HashRef]" would match "[1, {}]" but not "[{}, 1]".
136
137 "Dict[...]"
138 Subtype of "HashRef", accepting a list of type constraints for each
139 slot in the hash.
140
141 For example "Dict[name => Str, id => Int]" allows "{ name => "Bob",
142 id => 42 }".
143
144 "Optional[`a]"
145 Used in conjunction with "Dict" and "Tuple" to specify slots that
146 are optional and may be omitted (but not necessarily set to an
147 explicit undef).
148
149 "Dict[name => Str, id => Optional[Int]]" allows "{ name => "Bob" }"
150 but not "{ name => "Bob", id => "BOB" }".
151
152 Note that any use of "Optional[`a]" outside the context of
153 parameterized "Dict" and "Tuple" type constraints makes little
154 sense, and its behaviour is undefined. (An exception: it is used by
155 Type::Params for a similar purpose to how it's used in "Tuple".)
156
157 This module also exports a "slurpy" function, which can be used as
158 follows.
159
160 It can cause additional trailing values in a "Tuple" to be slurped into
161 a structure and validated. For example, slurping into an ArrayRef:
162
163 my $type = Tuple[Str, slurpy ArrayRef[Int]];
164
165 $type->( ["Hello"] ); # ok
166 $type->( ["Hello", 1, 2, 3] ); # ok
167 $type->( ["Hello", [1, 2, 3]] ); # not ok
168
169 Or into a hashref:
170
171 my $type2 = Tuple[Str, slurpy Map[Int, RegexpRef]];
172
173 $type2->( ["Hello"] ); # ok
174 $type2->( ["Hello", 1, qr/one/i, 2, qr/two/] ); # ok
175
176 It can cause additional values in a "Dict" to be slurped into a hashref
177 and validated:
178
179 my $type3 = Dict[ values => ArrayRef, slurpy HashRef[Str] ];
180
181 $type3->( { values => [] } ); # ok
182 $type3->( { values => [], name => "Foo" } ); # ok
183 $type3->( { values => [], name => [] } ); # not ok
184
185 In either "Tuple" or "Dict", "slurpy Any" can be used to indicate that
186 additional values are acceptable, but should not be constrained in any
187 way.
188
189 "slurpy Any" is an optimized code path. Although the following are
190 essentially equivalent checks, the former should run a lot faster:
191
192 Tuple[Int, slurpy Any]
193 Tuple[Int, slurpy ArrayRef]
194
195 Objects
196 OK, so I stole some ideas from MooX::Types::MooseLike::Base.
197
198 "InstanceOf[`a]"
199 Shortcut for a union of Type::Tiny::Class constraints.
200
201 "InstanceOf["Foo", "Bar"]" allows objects blessed into the "Foo" or
202 "Bar" classes, or subclasses of those.
203
204 Given no parameters, just equivalent to "Object".
205
206 "ConsumerOf[`a]"
207 Shortcut for an intersection of Type::Tiny::Role constraints.
208
209 "ConsumerOf["Foo", "Bar"]" allows objects where "$o->DOES("Foo")"
210 and "$o->DOES("Bar")" both return true.
211
212 Given no parameters, just equivalent to "Object".
213
214 "HasMethods[`a]"
215 Shortcut for a Type::Tiny::Duck constraint.
216
217 "HasMethods["foo", "bar"]" allows objects where "$o->can("foo")"
218 and "$o->can("bar")" both return true.
219
220 Given no parameters, just equivalent to "Object".
221
222 More
223 There are a few other types exported by this function:
224
225 "Overload[`a]"
226 With no parameters, checks that the value is an overloaded object.
227 Can be given one or more string parameters, which are specific
228 operations to check are overloaded. For example, the following
229 checks for objects which overload addition and subtraction.
230
231 Overload["+", "-"]
232
233 "Tied[`a]"
234 A reference to a tied scalar, array or hash.
235
236 Can be parameterized with a type constraint which will be applied
237 to the object returned by the "tied()" function. As a convenience,
238 can also be parameterized with a string, which will be inflated to
239 a Type::Tiny::Class.
240
241 use Types::Standard qw(Tied);
242 use Type::Utils qw(class_type);
243
244 my $My_Package = class_type { class => "My::Package" };
245
246 tie my %h, "My::Package";
247 \%h ~~ Tied; # true
248 \%h ~~ Tied[ $My_Package ]; # true
249 \%h ~~ Tied["My::Package"]; # true
250
251 tie my $s, "Other::Package";
252 \$s ~~ Tied; # true
253 $s ~~ Tied; # false !!
254
255 If you need to check that something is specifically a reference to
256 a tied hash, use an intersection:
257
258 use Types::Standard qw( Tied HashRef );
259
260 my $TiedHash = (Tied) & (HashRef);
261
262 tie my %h, "My::Package";
263 tie my $s, "Other::Package";
264
265 \%h ~~ $TiedHash; # true
266 \$s ~~ $TiedHash; # false
267
268 "StrMatch[`a]"
269 A string that matches a regular expression:
270
271 declare "Distance",
272 as StrMatch[ qr{^([0-9]+)\s*(mm|cm|m|km)$} ];
273
274 You can optionally provide a type constraint for the array of
275 subexpressions:
276
277 declare "Distance",
278 as StrMatch[
279 qr{^([0-9]+)\s*(.+)$},
280 Tuple[
281 Int,
282 enum(DistanceUnit => [qw/ mm cm m km /]),
283 ],
284 ];
285
286 Here's an example using Regexp::Common:
287
288 package Local::Host {
289 use Moose;
290 use Regexp::Common;
291 has ip_address => (
292 is => 'ro',
293 required => 1.
294 isa => StrMatch[/^$RE{net}{IPv4}$/],
295 default => '127.0.0.1',
296 );
297 }
298
299 On certain versions of Perl, type constraints of the forms
300 "StrMatch[qr/../" and "StrMatch[qr/\A..\z/" with any number of
301 intervening dots can be optimized to simple length checks.
302
303 "Enum[`a]"
304 As per MooX::Types::MooseLike::Base:
305
306 has size => (is => "ro", isa => Enum[qw( S M L XL XXL )]);
307
308 "OptList"
309 An arrayref of arrayrefs in the style of Data::OptList output.
310
311 "LaxNum", "StrictNum"
312 In Moose 2.09, the "Num" type constraint implementation was changed
313 from being a wrapper around Scalar::Util's "looks_like_number"
314 function to a stricter regexp (which disallows things like "-Inf"
315 and "Nan").
316
317 Types::Standard provides both implementations. "LaxNum" is
318 measurably faster.
319
320 The "Num" type constraint is currently an alias for "LaxNum" unless
321 you set the "PERL_TYPES_STANDARD_STRICTNUM" environment variable to
322 true before loading Types::Standard, in which case it becomes an
323 alias for "StrictNum". The constant "Types::Standard::STRICTNUM"
324 can be used to check if "Num" is being strict.
325
326 Most people should probably use "Num" or "StrictNum". Don't
327 explicitly use "LaxNum" unless you specifically need an attribute
328 which will accept things like "Inf".
329
330 "CycleTuple[`a]"
331 Similar to Tuple, but cyclical.
332
333 CycleTuple[Int, HashRef]
334
335 will allow "[1,{}]" and "[1,{},2,{}]" but disallow "[1,{},2]" and
336 "[1,{},2,[]]".
337
338 I think you understand CycleTuples already.
339
340 Currently "Optional" and "slurpy" parameters are forbidden. There
341 are fairly limited use cases for them, and it's not exactly clear
342 what they should mean.
343
344 The following is an efficient way of checking for an even-sized
345 arrayref:
346
347 CycleTuple[Any, Any]
348
349 The following is an arrayref which would be suitable for coercing
350 to a hashref:
351
352 CycleTuple[Str, Any]
353
354 All the examples so far have used two parameters, but the following
355 is also a possible CycleTuple:
356
357 CycleTuple[Str, Int, HashRef]
358
359 This will be an arrayref where the 0th, 3rd, 6th, etc values are
360 strings, the 1st, 4th, 7th, etc values are integers, and the 2nd,
361 5th, 8th, etc values are hashrefs.
362
363 Coercions
364 Most of the types in this type library have no coercions by default.
365 The exception is "Bool" as of Types::Standard 1.003_003, which coerces
366 from "Any" via "!!$_".
367
368 Some standalone coercions may be exported. These can be combined with
369 type constraints using the "plus_coercions" method.
370
371 "MkOpt"
372 A coercion from "ArrayRef", "HashRef" or "Undef" to "OptList".
373 Example usage in a Moose attribute:
374
375 use Types::Standard qw( OptList MkOpt );
376
377 has options => (
378 is => "ro",
379 isa => OptList->plus_coercions( MkOpt ),
380 coerce => 1,
381 );
382
383 "Split[`a]"
384 Split a string on a regexp.
385
386 use Types::Standard qw( ArrayRef Str Split );
387
388 has name => (
389 is => "ro",
390 isa => (ArrayRef[Str])->plus_coercions(Split[qr/\s/]),
391 coerce => 1,
392 );
393
394 "Join[`a]"
395 Join an array of strings with a delimiter.
396
397 use Types::Standard qw( Str Join );
398
399 my $FileLines = Str->plus_coercions(Join["\n"]);
400
401 has file_contents => (
402 is => "ro",
403 isa => $FileLines,
404 coerce => 1,
405 );
406
407 Constants
408 "Types::Standard::STRICTNUM"
409 Indicates whether "Num" is an alias for "StrictNum". (It is usually
410 an alias for "LaxNum".)
411
412 Environment
413 "PERL_TYPES_STANDARD_STRICTNUM"
414 Switches to more strict regexp-based number checking instead of
415 using "looks_like_number".
416
417 "PERL_TYPE_TINY_XS"
418 If set to false, can be used to suppress the loading of XS
419 implementions of some type constraints.
420
421 "PERL_ONLY"
422 If "PERL_TYPE_TINY_XS" does not exist, can be set to true to
423 suppress XS usage similarly. (Several other CPAN distributions also
424 pay attention to this environment variable.)
425
427 Please report any bugs to
428 <http://rt.cpan.org/Dist/Display.html?Queue=Type-Tiny>.
429
431 Type::Tiny::Manual.
432
433 Type::Tiny, Type::Library, Type::Utils, Type::Coercion.
434
435 Moose::Util::TypeConstraints, Mouse::Util::TypeConstraints,
436 MooseX::Types::Structured.
437
438 Types::XSD provides some type constraints based on XML Schema's data
439 types; this includes constraints for ISO8601-formatted datetimes,
440 integer ranges (e.g. "PositiveInteger[maxInclusive=>10]" and so on.
441
442 Types::Encodings provides "Bytes" and "Chars" type constraints that
443 were formerly found in Types::Standard.
444
445 Types::Common::Numeric and Types::Common::String provide replacements
446 for MooseX::Types::Common.
447
449 Toby Inkster <tobyink@cpan.org>.
450
452 This software is copyright (c) 2013-2014, 2017-2019 by Toby Inkster.
453
454 This is free software; you can redistribute it and/or modify it under
455 the same terms as the Perl 5 programming language system itself.
456
458 THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
459 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
460 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
461
462
463
464perl v5.30.0 2019-07-26 Types::Standard(3)