]> Dogcows Code - chaz/p5-Return-Type-Lexical/blob - lib/Return/Type/Lexical.pm
83d4ec1d3bc9eb7c4c27d31635249121123e5b24
[chaz/p5-Return-Type-Lexical] / lib / Return / Type / Lexical.pm
1 package Return::Type::Lexical;
2 # ABSTRACT: Same thing as Return::Type, but lexical
3
4 use 5.008;
5 use warnings;
6 use strict;
7
8 use parent 'Return::Type';
9
10 our $VERSION = '0.001'; # VERSION
11
12 sub import {
13 my ($class, %args) = @_;
14 $^H{'Return::Type::Lexical/in_effect'} = exists $args{check} && !$args{check} ? 0 : 1;
15 }
16
17 sub unimport {
18 $^H{'Return::Type::Lexical/in_effect'} = 0;
19 }
20
21 sub _in_effect {
22 my $level = shift // 0;
23 my $hinthash = (caller($level))[10];
24 my $in_effect = $hinthash->{'Return::Type::Lexical/in_effect'};
25 return !defined $in_effect || $in_effect;
26 }
27
28 my $handler;
29 BEGIN {
30 $handler = $UNIVERSAL::{ReturnType};
31 delete $UNIVERSAL::{ReturnType};
32 delete $UNIVERSAL::{_ATTR_CODE_ReturnType};
33 }
34 sub UNIVERSAL::ReturnType :ATTR(CODE,BEGIN) {
35 my $in_effect = _in_effect(4);
36 return if !$in_effect;
37
38 return $handler->(@_);
39 }
40
41 1;
42
43 __END__
44
45 =pod
46
47 =encoding UTF-8
48
49 =head1 NAME
50
51 Return::Type::Lexical - Same thing as Return::Type, but lexical
52
53 =head1 VERSION
54
55 version 0.001
56
57 =head1 SYNOPSIS
58
59 use Return::Type::Lexical;
60 use Types::Standard qw(Int);
61
62 sub foo :ReturnType(Int) { return "not an int" }
63
64 {
65 no Return::Type::Lexical;
66 sub bar :ReturnType(Int) { return "not an int" }
67 }
68
69 my $foo = foo(); # throws an error
70 my $bar = bar(); # returns "not an int"
71
72 # Can also be used with Devel::StrictMode to only perform
73 # type checks in strict mode:
74
75 use Devel::StrictMode;
76 use Return::Type::Lexical check => STRICT;
77
78 =head1 DESCRIPTION
79
80 This module works just like L<Return::Type>, but type-checking can be enabled and disabled within
81 lexical scopes.
82
83 There is no runtime penalty when type-checking is disabled.
84
85 =head1 METHODS
86
87 =head2 import
88
89 The C<check> attribute can be used to set whether or not types are checked.
90
91 =head1 BUGS
92
93 Please report any bugs or feature requests on the bugtracker website
94 L<https://github.com/chazmcgarvey/Return-Type-Lexical/issues>
95
96 When submitting a bug or request, please include a test-file or a
97 patch to an existing test-file that illustrates the bug or desired
98 feature.
99
100 =head1 AUTHOR
101
102 Charles McGarvey <chazmcgarvey@brokenzipper.com>
103
104 =head1 COPYRIGHT AND LICENSE
105
106 This software is copyright (c) 2020 by Charles McGarvey.
107
108 This is free software; you can redistribute it and/or modify it under
109 the same terms as the Perl 5 programming language system itself.
110
111 =cut
This page took 0.042023 seconds and 3 git commands to generate.