|No such thing as a small change|
Exploring Type::Tiny Part 3: Using Type::Tieby tobyink (Abbot)
|on Aug 08, 2018 at 17:02 UTC||Need Help??|
Type::Tiny is probably best known as a way of having Moose-like type constraints in Moo, but it can be used for so much more. This is the third in a series of posts showing other things you can use Type::Tiny for. This article along with part 1 and part 2 can be found on my blog and in the Cool Uses for Perl section of PerlMonks.
Well, if you try it, you may find it complains about not being able to load Type::Tie.
Type::Tie is an add-on for Type::Tiny distributed separately. It's an optional dependency, so if you want to use this feature, you'll need to make sure it's installed.
This tie feature automatically supports coercions.
More about Type::Tie
To save yourself typing "Type::Tie::ARRAY", "Type::Tie::HASH", and "Type::Tie::SCALAR" all the time, Type::Tie offers a convenience function ttie:
Use in Attributes
Perl has a type checking hole thanks to references:
The type constraint is only checked in the constructor and in writers/accessors.
Tying the array allows you to perform type checks and coercions on any new elements added to the array. It's a use for trigger that doesn't suck!
With a little bit of work (okay, a lot!) it should be possible to even check deeply nested structures.
While effort has been made to optimize Type::Tie, tied variables are necessarily slower than untied ones.
If you have an array you want to make sure only contains integers, but you don't want to compromise on performance, you could enable the tie only when you run your test suite, and trust that your test suite will be enough to trigger any potential errors.
Devel::StrictMode is a module which exports a constant called STRICT which will be true if the PERL_STRICT, EXTENDED_TESTING, RELEASE_TESTING, or AUTHOR_TESTING environment variables is true, and false otherwise.