4 @EXPORT = qw(AUTOLOAD);
9 my %Cache; # private cache for all SelfLoader's client packages
11 # allow checking for valid ': attrlist' attachments
12 # (we use 'our' rather than 'my' here, due to the rather complex and buggy
13 # behaviour of lexicals with qr// and (??{$lex}) )
15 $nested = qr{ \( (?: (?> [^()]+ ) | (??{ $nested }) )* \) }x;
16 our $one_attr = qr{ (?> (?! \d) \w+ (?:$nested)? ) (?:\s*\:\s*|\s+(?!\:)) }x;
17 our $attr_list = qr{ \s* : \s* (?: $one_attr )* }x;
19 # in croak and carp, protect $@ from "require Carp;" RT #40216
21 sub croak { { local $@; require Carp; } goto &Carp::croak }
22 sub carp { { local $@; require Carp; } goto &Carp::carp }
25 print STDERR "SelfLoader::AUTOLOAD for $AUTOLOAD\n" if $DEBUG;
26 my $SL_code = $Cache{$AUTOLOAD};
27 my $save = $@; # evals in both AUTOLOAD and _load_stubs can corrupt $@
29 # Maybe this pack had stubs before __DATA__, and never initialized.
30 # Or, this maybe an automatic DESTROY method call when none exists.
31 $AUTOLOAD =~ m/^(.*)::/;
32 SelfLoader->_load_stubs($1) unless exists $Cache{"${1}::<DATA"};
33 $SL_code = $Cache{$AUTOLOAD};
34 $SL_code = "sub $AUTOLOAD { }"
35 if (!$SL_code and $AUTOLOAD =~ m/::DESTROY$/);
36 croak "Undefined subroutine $AUTOLOAD" unless $SL_code;
38 print STDERR "SelfLoader::AUTOLOAD eval: $SL_code\n" if $DEBUG;
46 defined(&$AUTOLOAD) || die "SelfLoader inconsistency error";
47 delete $Cache{$AUTOLOAD};
51 sub load_stubs { shift->_load_stubs((caller)[0]) }
54 # $endlines is used by Devel::SelfStubber to capture lines after __END__
55 my($self, $callpack, $endlines) = @_;
56 my $fh = \*{"${callpack}::DATA"};
57 my $currpack = $callpack;
58 my($line,$name,@lines, @stubs, $protoype);
60 print STDERR "SelfLoader::load_stubs($callpack)\n" if $DEBUG;
61 croak("$callpack doesn't contain an __DATA__ token")
62 unless defined fileno($fh);
63 # Protect: fork() shares the file pointer between the parent and the kid
64 open my $nfh, '<&', $fh or croak "reopen: $!";# dup() the fd
65 close $fh or die "close: $1"; # autocloses, but be paranoid
66 open $fh, '<&', $nfh or croak "reopen2: $!"; # dup() the fd "back"
67 close $nfh or die "close after reopen: $1"; # autocloses, but be paranoid
68 $Cache{"${currpack}::<DATA"} = 1; # indicate package is cached
71 while(defined($line = <$fh>) and $line !~ m/^__END__/) {
72 if ($line =~ m/^sub\s+([\w:]+)\s*((?:\([\\\$\@\%\&\*\;]*\))?(?:$attr_list)?)/) {
73 push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
76 if (index($1,'::') == -1) { # simple sub name
77 $name = "${currpack}::$1";
78 } else { # sub name with package
81 if (defined(&{"${1}::AUTOLOAD"})) {
82 \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
83 die 'SelfLoader Error: attempt to specify Selfloading',
84 " sub $name in non-selfloading module $1";
86 $self->export($1,'AUTOLOAD');
89 } elsif ($line =~ m/^package\s+([\w:]+)/) { # A package declared
90 push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
91 $self->_package_defined($line);
95 $Cache{"${currpack}::<DATA"} = 1; # indicate package is cached
96 if (defined(&{"${1}::AUTOLOAD"})) {
97 \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
98 die 'SelfLoader Error: attempt to specify Selfloading',
99 " package $currpack which already has AUTOLOAD";
101 $self->export($currpack,'AUTOLOAD');
107 if (defined($line) && $line =~ /^__END__/) { # __END__
108 unless ($line =~ /^__END__\s*DATA/) {
110 # Devel::SelfStubber would like us to capture the lines after
111 # __END__ so it can write out the entire file
117 push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
118 eval join('', @stubs) if @stubs;
123 my($self,$fullname,$pack,$lines, $protoype) = @_;
124 return () unless $fullname;
125 carp("Redefining sub $fullname")
126 if exists $Cache{$fullname};
127 $Cache{$fullname} = join('', "package $pack; ",@$lines);
128 print STDERR "SelfLoader cached $fullname: $Cache{$fullname}" if $DEBUG;
129 # return stub to be eval'd
130 defined($protoype) ? "sub $fullname $protoype;" : "sub $fullname;"
133 sub _package_defined {}
140 SelfLoader - load functions only on demand
147 ... (initializing code)
155 This module tells its users that functions in the FOOBAR package are to be
156 autoloaded from after the C<__DATA__> token. See also
157 L<perlsub/"Autoloading">.
159 =head2 The __DATA__ token
161 The C<__DATA__> token tells the perl compiler that the perl code
162 for compilation is finished. Everything after the C<__DATA__> token
163 is available for reading via the filehandle FOOBAR::DATA,
164 where FOOBAR is the name of the current package when the C<__DATA__>
165 token is reached. This works just the same as C<__END__> does in
166 package 'main', but for other modules data after C<__END__> is not
167 automatically retrievable, whereas data after C<__DATA__> is.
168 The C<__DATA__> token is not recognized in versions of perl prior to
171 Note that it is possible to have C<__DATA__> tokens in the same package
172 in multiple files, and that the last C<__DATA__> token in a given
173 package that is encountered by the compiler is the one accessible
174 by the filehandle. This also applies to C<__END__> and main, i.e. if
175 the 'main' program has an C<__END__>, but a module 'require'd (_not_ 'use'd)
176 by that program has a 'package main;' declaration followed by an 'C<__DATA__>',
177 then the C<DATA> filehandle is set to access the data after the C<__DATA__>
178 in the module, _not_ the data after the C<__END__> token in the 'main'
179 program, since the compiler encounters the 'require'd file later.
181 =head2 SelfLoader autoloading
183 The B<SelfLoader> works by the user placing the C<__DATA__>
184 token I<after> perl code which needs to be compiled and
185 run at 'require' time, but I<before> subroutine declarations
186 that can be loaded in later - usually because they may never
189 The B<SelfLoader> will read from the FOOBAR::DATA filehandle to
190 load in the data after C<__DATA__>, and load in any subroutine
191 when it is called. The costs are the one-time parsing of the
192 data after C<__DATA__>, and a load delay for the _first_
193 call of any autoloaded function. The benefits (hopefully)
194 are a speeded up compilation phase, with no need to load
195 functions which are never used.
197 The B<SelfLoader> will stop reading from C<__DATA__> if
198 it encounters the C<__END__> token - just as you would expect.
199 If the C<__END__> token is present, and is followed by the
200 token DATA, then the B<SelfLoader> leaves the FOOBAR::DATA
201 filehandle open on the line after that token.
203 The B<SelfLoader> exports the C<AUTOLOAD> subroutine to the
204 package using the B<SelfLoader>, and this loads the called
205 subroutine when it is first called.
207 There is no advantage to putting subroutines which will _always_
208 be called after the C<__DATA__> token.
210 =head2 Autoloading and package lexicals
212 A 'my $pack_lexical' statement makes the variable $pack_lexical
213 local _only_ to the file up to the C<__DATA__> token. Subroutines
214 declared elsewhere _cannot_ see these types of variables,
215 just as if you declared subroutines in the package but in another
216 file, they cannot see these variables.
218 So specifically, autoloaded functions cannot see package
219 lexicals (this applies to both the B<SelfLoader> and the Autoloader).
220 The C<vars> pragma provides an alternative to defining package-level
221 globals that will be visible to autoloaded routines. See the documentation
222 on B<vars> in the pragma section of L<perlmod>.
224 =head2 SelfLoader and AutoLoader
226 The B<SelfLoader> can replace the AutoLoader - just change 'use AutoLoader'
227 to 'use SelfLoader' (though note that the B<SelfLoader> exports
228 the AUTOLOAD function - but if you have your own AUTOLOAD and
229 are using the AutoLoader too, you probably know what you're doing),
230 and the C<__END__> token to C<__DATA__>. You will need perl version 5.001m
231 or later to use this (version 5.001 with all patches up to patch m).
233 There is no need to inherit from the B<SelfLoader>.
235 The B<SelfLoader> works similarly to the AutoLoader, but picks up the
236 subs from after the C<__DATA__> instead of in the 'lib/auto' directory.
237 There is a maintenance gain in not needing to run AutoSplit on the module
238 at installation, and a runtime gain in not needing to keep opening and
239 closing files to load subs. There is a runtime loss in needing
240 to parse the code after the C<__DATA__>. Details of the B<AutoLoader> and
241 another view of these distinctions can be found in that module's
244 =head2 __DATA__, __END__, and the FOOBAR::DATA filehandle.
246 This section is only relevant if you want to use
247 the C<FOOBAR::DATA> together with the B<SelfLoader>.
249 Data after the C<__DATA__> token in a module is read using the
250 FOOBAR::DATA filehandle. C<__END__> can still be used to denote the end
251 of the C<__DATA__> section if followed by the token DATA - this is supported
252 by the B<SelfLoader>. The C<FOOBAR::DATA> filehandle is left open if an
253 C<__END__> followed by a DATA is found, with the filehandle positioned at
254 the start of the line after the C<__END__> token. If no C<__END__> token is
255 present, or an C<__END__> token with no DATA token on the same line, then
256 the filehandle is closed.
258 The B<SelfLoader> reads from wherever the current
259 position of the C<FOOBAR::DATA> filehandle is, until the
260 EOF or C<__END__>. This means that if you want to use
261 that filehandle (and ONLY if you want to), you should either
263 1. Put all your subroutine declarations immediately after
264 the C<__DATA__> token and put your own data after those
265 declarations, using the C<__END__> token to mark the end
266 of subroutine declarations. You must also ensure that the B<SelfLoader>
267 reads first by calling 'SelfLoader-E<gt>load_stubs();', or by using a
268 function which is selfloaded;
272 2. You should read the C<FOOBAR::DATA> filehandle first, leaving
273 the handle open and positioned at the first line of subroutine
276 You could conceivably do both.
278 =head2 Classes and inherited methods.
280 For modules which are not classes, this section is not relevant.
281 This section is only relevant if you have methods which could
284 A subroutine stub (or forward declaration) looks like
288 i.e. it is a subroutine declaration without the body of the
289 subroutine. For modules which are not classes, there is no real
290 need for stubs as far as autoloading is concerned.
292 For modules which ARE classes, and need to handle inherited methods,
293 stubs are needed to ensure that the method inheritance mechanism works
294 properly. You can load the stubs into the module at 'require' time, by
295 adding the statement 'SelfLoader-E<gt>load_stubs();' to the module to do
298 The alternative is to put the stubs in before the C<__DATA__> token BEFORE
299 releasing the module, and for this purpose the C<Devel::SelfStubber>
300 module is available. However this does require the extra step of ensuring
301 that the stubs are in the module. If this is done I strongly recommend
302 that this is done BEFORE releasing the module - it should NOT be done
303 at install time in general.
305 =head1 Multiple packages and fully qualified subroutine names
307 Subroutines in multiple packages within the same file are supported - but you
308 should note that this requires exporting the C<SelfLoader::AUTOLOAD> to
309 every package which requires it. This is done automatically by the
310 B<SelfLoader> when it first loads the subs into the cache, but you should
311 really specify it in the initialization before the C<__DATA__> by putting
312 a 'use SelfLoader' statement in each package.
314 Fully qualified subroutine names are also supported. For example,
321 will all be loaded correctly by the B<SelfLoader>, and the B<SelfLoader>
322 will ensure that the packages 'foo' and 'baz' correctly have the
323 B<SelfLoader> C<AUTOLOAD> method when the data after C<__DATA__> is first