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