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