1Types::Standard(3)    User Contributed Perl Documentation   Types::Standard(3)
2
3
4

NAME

6       Types::Standard - bundled set of built-in types for Type::Tiny
7

SYNOPSIS

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

STATUS

75       This module is covered by the Type-Tiny stability policy.
76

DESCRIPTION

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

BUGS

567       Please report any bugs to
568       <https://github.com/tobyink/p5-type-tiny/issues>.
569

SEE ALSO

571       The Type::Tiny homepage <https://typetiny.toby.ink/>.
572
573       Type::Tiny::Manual.
574
575       Type::Tiny, Type::Library, Type::Utils, Type::Coercion.
576
577       Moose::Util::TypeConstraints, Mouse::Util::TypeConstraints,
578       MooseX::Types::Structured.
579
580       Types::XSD provides some type constraints based on XML Schema's data
581       types; this includes constraints for ISO8601-formatted datetimes,
582       integer ranges (e.g. PositiveInteger[maxInclusive=>10] and so on.
583
584       Types::Encodings provides Bytes and Chars type constraints that were
585       formerly found in Types::Standard.
586
587       Types::Common::Numeric and Types::Common::String provide replacements
588       for MooseX::Types::Common.
589

AUTHOR

591       Toby Inkster <tobyink@cpan.org>.
592
594       This software is copyright (c) 2013-2014, 2017-2023 by Toby Inkster.
595
596       This is free software; you can redistribute it and/or modify it under
597       the same terms as the Perl 5 programming language system itself.
598

DISCLAIMER OF WARRANTIES

600       THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
601       WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
602       MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
603
604
605
606perl v5.38.0                      2023-07-21                Types::Standard(3)
Impressum