]> Dogcows Code - chaz/p5-Return-Type-Lexical/blob - lib/Return/Type/Lexical.pm
873d447e87175332d9b4202c9411767525f1d56d
[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) = @_;
23 $level = 0 if !defined $level;
24 my $hinthash = (caller($level))[10];
25 my $in_effect = $hinthash->{'Return::Type::Lexical/in_effect'};
26 return !defined $in_effect || $in_effect;
27 }
28
29 my $handler;
30 BEGIN {
31 $handler = $UNIVERSAL::{ReturnType};
32 delete $UNIVERSAL::{ReturnType};
33 delete $UNIVERSAL::{_ATTR_CODE_ReturnType};
34 }
35 sub UNIVERSAL::ReturnType :ATTR(CODE,BEGIN) {
36 my $in_effect = _in_effect(4);
37 return if !$in_effect;
38
39 return $handler->(@_);
40 }
41
42 1;
43 __END__
44
45 =head1 SYNOPSIS
46
47 use Return::Type::Lexical;
48 use Types::Standard qw(Int);
49
50 sub foo :ReturnType(Int) { return "not an int" }
51
52 {
53 no Return::Type::Lexical;
54 sub bar :ReturnType(Int) { return "not an int" }
55 }
56
57 my $foo = foo(); # throws an error
58 my $bar = bar(); # returns "not an int"
59
60 # Can also be used with Devel::StrictMode to only perform
61 # type checks in strict mode:
62
63 use Devel::StrictMode;
64 use Return::Type::Lexical check => STRICT;
65
66 =head1 DESCRIPTION
67
68 This module works just like L<Return::Type>, but type-checking can be enabled and disabled within
69 lexical scopes.
70
71 There is no runtime penalty when type-checking is disabled.
72
73 =method import
74
75 The C<check> attribute can be used to set whether or not types are checked.
76
77 =cut
This page took 0.036692 seconds and 3 git commands to generate.