File Coverage

blib/lib/Lexical/Import.pm
Criterion Covered Total %
statement 66 66 100.0
branch 23 24 95.8
condition n/a
subroutine 13 13 100.0
pod n/a
total 102 103 99.0


line stmt bran cond sub pod time code
1             =head1 NAME
2              
3             Lexical::Import - clean imports from package-exporting modules
4              
5             =head1 SYNOPSIS
6              
7             use Lexical::Import "Carp";
8              
9             use Lexical::Import qw(Time::HiRes time sleep);
10              
11             use Lexical::Import qw(Fcntl-1.01 :flock);
12              
13             use Lexical::Import (
14             ["Carp"],
15             [qw(Time::HiRes time sleep)],
16             [qw(Fcntl-1.01 :flock)],
17             );
18              
19             =head1 DESCRIPTION
20              
21             This module allows functions and other items, from a separate
22             module, to be imported into the lexical namespace (as implemented by
23             L), when the exporting module exports non-lexically to
24             a package in the traditional manner. This is a translation layer,
25             to help code written in the new way to use modules written in the old way.
26              
27             A lexically-imported item takes effect from the end of the definition
28             statement up to the end of the immediately enclosing block, except
29             where it is shadowed within a nested block. This is the same lexical
30             scoping that the C, C, and C keywords supply. Within its
31             scope, any use of the single-part name of the item (e.g., "C<$foo>")
32             refers directly to that item, regardless of what is in any package.
33             Explicitly package-qualified names (e.g., "C<$main::foo>") still refer
34             to the package. There is no conflict between a lexical name definition
35             and the same name in any package.
36              
37             This mechanism only works on Perl 5.11.2 and later. Prior to that,
38             it is impossible for lexical subroutine imports to work for bareword
39             subroutine calls. (See L for details.) Other kinds
40             of lexical importing are possible on earlier Perls, but because this is
41             such a critical kind of usage in most code, this module will ensure that
42             it works, for convenience. If the limited lexical importing is desired
43             on earlier Perls, use L directly.
44              
45             =cut
46              
47             package Lexical::Import;
48              
49 4     4   53299 { use 5.011002; }
  4         15  
  4         156  
50 4     4   24 use warnings;
  4         9  
  4         147  
51 4     4   31 use strict;
  4         9  
  4         153  
52              
53 4     4   21 use Carp qw(croak);
  4         9  
  4         330  
54 4     4   9588 use Lexical::Var 0.006 ();
  4         9622  
  4         120  
55 4     4   3417 use Module::Runtime 0.011 qw($module_name_rx require_module);
  4         7113  
  4         22  
56 4     4   3569 use Params::Classify 0.000 qw(is_string is_ref);
  4         8497  
  4         394  
57 4     4   3760 use version 0.81 ();
  4         8750  
  4         330  
58              
59             our $VERSION = "0.002";
60              
61             require XSLoader;
62             XSLoader::load(__PACKAGE__, $VERSION);
63              
64             =head1 PACKAGE METHODS
65              
66             These methods are meant to be invoked on the C package.
67              
68             =over
69              
70             =item Lexical::Import->import(MODULE_NAME, ARGS ...)
71              
72             I must be a Perl module name, in bareword syntax with C<::>
73             separators. The named module is loaded, and its C method is
74             called with the supplied I. It is expected to insert some set of
75             functions and other items to the package from which its C method
76             was called. Whatever scalars, arrays, hashes, and subroutines it thus
77             exported are added to the lexical environment that is currently compiling.
78              
79             The overall effect, when this is performed at compile time (usually via
80             C), is that a C is performed on the I and I,
81             with all of the module's package-based exporting being turned into
82             lexical exporting. If the exporting module does some lexical exporting
83             of its own, that will still work correctly when done by this indirect
84             mechanism, but there is no point to the indirection if the exporting
85             module uses lexical exporting exclusively.
86              
87             Optionally, I may be suffixed with a version number,
88             separated from the module name by a "C<->". The version number must
89             conform to the "strict" syntax (see L). If this
90             is done, then after loading the module it will be checked that what was
91             loaded is at least the specified version. For example, "C"
92             requests the C module, version 1.01 or later. This check is
93             actually performed by calling the C method of the module, so the
94             module can redefine it to have effects other than version checking, which
95             some modules do even though it shows poor taste. Any items exported by
96             C into the calling package will be picked up and added to the
97             lexical environment, just as if they had been exported by C.
98              
99             Optionally, I may be prefixed with a "C<->", in which
100             case the module's C method is called instead of C.
101             This effectively performs a C instead of a C. This is meant
102             to handle the few modules which, in poor taste, switch the conventional
103             meanings of C and C.
104              
105             =item Lexical::Import->import(IMPORT_LIST, ...)
106              
107             There must be one or more I, each of which is a reference
108             to an array containing a I and I as described for
109             the preceding form of C. Each such list is processed in turn
110             for importing. This is a shorthand for where several invocations of
111             this module would otherwise be required.
112              
113             =cut
114              
115             sub Lexical::Import::__DELETE_STAGE::DESTROY {
116 4     4   28 no strict "refs";
  4         8  
  4         1720  
117 30     30   16125 delete $Lexical::Import::{$_[0]->{name}."::"};
118             }
119              
120             my $next_stagenum = 0;
121              
122             sub import {
123 39     39   27738 my $class = shift;
124 39 100       301 croak "$class does no default importation" if @_ == 0;
125 38 100       137 foreach my $arglist (is_ref($_[0], "ARRAY") ? @_ : (\@_)) {
126 40 100       241 croak "non-array in $class multi-import list"
127             unless is_ref($arglist, "ARRAY");
128 39 100       309 croak "$class needs the name of a module to import from"
129             unless is_string($arglist->[0]);
130 37         462 my($no, $mname, $reqver) =
131             ($arglist->[0] =~
132             /\A(-)?($module_name_rx)(?:-($version::STRICT))?\z/o);
133 37 100       100 croak "malformed module name `@{[$arglist->[0]]}'"
  7         803  
134             unless defined $mname;
135 30         602 require_module($mname);
136 30         10321 my $stagename = "__STAGE".($next_stagenum++);
137 30         51 my $stagepkg = "Lexical::Import::".$stagename;
138 30         138 my $cleanup_stage = bless({name=>$stagename},
139             "Lexical::Import::__DELETE_STAGE");
140 4     4   50 no strict "refs";
  4         9  
  4         1577  
141 30         40 %{$stagepkg."::"} = ();
  30         241  
142 30         3382 eval(qq{
143             package $stagepkg;
144             sub {
145             my \$mname = shift;
146             my \$reqver = shift;
147             my \$import = shift;
148             \$mname->VERSION(\$reqver) if defined \$reqver;
149             \$mname->\$import(\@_);
150             }
151             })->(
152             $mname, $reqver, $no ? "unimport" : "import",
153 30 100       104 @{$arglist}[1..$#$arglist],
154             );
155 23         778 my @imports;
156 23         42 foreach my $name (keys %{$stagepkg."::"}) {
  23         94  
157 53 50       212 next unless $name =~ /\A[A-Z_a-z][0-9A-Z_a-z]*\z/;
158 53         58 my $glob = \*{$stagepkg."::".$name};
  53         2461  
159 53 100       155 push @imports, "\$".$name, *{$glob}{SCALAR}
  11         31  
160             if _glob_has_scalar($glob);
161 2         4 push @imports, "\@".$name, *{$glob}{ARRAY}
  53         121  
162 53 100       58 if defined *{$glob}{ARRAY};
163 2         4 push @imports, "%".$name, *{$glob}{HASH}
  53         105  
164 53 100       56 if defined *{$glob}{HASH};
165 17         52 push @imports, "&".$name, *{$glob}{CODE}
  53         160  
166 53 100       57 if defined *{$glob}{CODE};
167             }
168 23 100       297 Lexical::Var->import(@imports) if @imports;
169             }
170             }
171              
172             =item Lexical::Import->unimport
173              
174             Unimportation is not supported by this module, so this method just
175             Cs.
176              
177             =cut
178              
179 1     1   526 sub unimport { croak "$_[0] does not support unimportation" }
180              
181             =back
182              
183             =head1 BUGS
184              
185             Only scalars, arrays, hashes, and subroutines can be translated from the
186             package namespace to the lexical namespace. If a module exports more
187             exotic items, such as bareword I/O handles or formats, they will be lost.
188              
189             If an exporting module does anything more complex than just inserting
190             items into the calling package, this is liable to fail. For example, if
191             it records the name of the calling package for some functional purpose
192             then this won't work as intended: it will get the name of a temporary
193             package that doesn't exist once the importing is complete.
194              
195             If an exporting module tries to read a variable in the calling package,
196             this will fail in two ways. Firstly, because it sees a temporary
197             package, it won't pick up any variable from the real caller. Secondly,
198             it is liable to bring the variable into existence (with an empty value),
199             which looks like it exported the variable, so the empty variable will
200             be lexically imported by the real caller.
201              
202             Subroutine calls, to lexically-imported subroutines, that have neither
203             sigil nor parentheses (around the argument list) are subject to an
204             ambiguity with indirect object syntax. If the first argument expression
205             begins with a bareword or a scalar variable reference then the Perl
206             parser is liable to interpret the call as an indirect method call.
207             Normally this syntax would be interpreted as a subroutine call if the
208             subroutine exists, but the parser doesn't look at lexically-defined
209             subroutines for this purpose. The call interpretation can be forced by
210             prefixing the first argument expression with a C<+>, or by wrapping the
211             whole argument list in parentheses.
212              
213             If this package's C method is called from inside a string
214             C inside a C block, it does not have proper access to the
215             compiling environment, and will complain that it is being invoked outside
216             compilation. Calling from the body of a Cd or Ced file
217             causes the same problem. Other kinds of indirection within a C
218             block, such as calling via a normal function, do not cause this problem.
219             Ultimately this is a problem with the Perl core, and may change in a
220             future version.
221              
222             =head1 SEE ALSO
223              
224             L,
225             L
226              
227             =head1 AUTHOR
228              
229             Andrew Main (Zefram)
230              
231             =head1 COPYRIGHT
232              
233             Copyright (C) 2010, 2011 Andrew Main (Zefram)
234              
235             =head1 LICENSE
236              
237             This module is free software; you can redistribute it and/or modify it
238             under the same terms as Perl itself.
239              
240             =cut
241              
242             1;