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 = 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

STATUS

73       This module is covered by the Type-Tiny stability policy.
74

DESCRIPTION

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

BUGS

539       Please report any bugs to
540       <http://rt.cpan.org/Dist/Display.html?Queue=Type-Tiny>.
541

SEE ALSO

543       The Type::Tiny homepage <http://typetiny.toby.ink/>.
544
545       Type::Tiny::Manual.
546
547       Type::Tiny, Type::Library, Type::Utils, Type::Coercion.
548
549       Moose::Util::TypeConstraints, Mouse::Util::TypeConstraints,
550       MooseX::Types::Structured.
551
552       Types::XSD provides some type constraints based on XML Schema's data
553       types; this includes constraints for ISO8601-formatted datetimes,
554       integer ranges (e.g. PositiveInteger[maxInclusive=>10] and so on.
555
556       Types::Encodings provides Bytes and Chars type constraints that were
557       formerly found in Types::Standard.
558
559       Types::Common::Numeric and Types::Common::String provide replacements
560       for MooseX::Types::Common.
561

AUTHOR

563       Toby Inkster <tobyink@cpan.org>.
564
566       This software is copyright (c) 2013-2014, 2017-2020 by Toby Inkster.
567
568       This is free software; you can redistribute it and/or modify it under
569       the same terms as the Perl 5 programming language system itself.
570

DISCLAIMER OF WARRANTIES

572       THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
573       WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
574       MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
575
576
577
578perl v5.30.1                      2020-02-12                Types::Standard(3)
Impressum