]> Dogcows Code - chaz/p5-Return-Type-Lexical/blob - lib/Return/Type/Lexical.pm
a6d58073a0a3c0535a0af10f867c57037df1c507
[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 = '999.999'; # 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 __END__
43
44 =head1 SYNOPSIS
45
46 use Return::Type::Lexical;
47 use Types::Standard qw(Int);
48
49 sub foo :ReturnType(Int) { return "not an int" }
50
51 {
52 no Return::Type::Lexical;
53 sub bar :ReturnType(Int) { return "not an int" }
54 }
55
56 my $foo = foo(); # throws an error
57 my $bar = bar(); # returns "not an int"
58
59 # Can also be used with Devel::StrictMode to only perform
60 # type checks in strict mode:
61
62 use Devel::StrictMode;
63 use Return::Type::Lexical check => STRICT;
64
65 =head1 DESCRIPTION
66
67 This module works just like L<Return::Type>, but type-checking can be enabled and disabled within
68 lexical scopes.
69
70 There is no runtime penalty when type-checking is disabled.
71
72 =method import
73
74 The C<check> attribute can be used to set whether or not types are checked.
75
76 =cut
This page took 0.03295 seconds and 3 git commands to generate.