3 use 5.009005; # due to new regexp features
7 our @ISA = qw(Exporter);
8 our @EXPORT = qw(AUTOLOAD);
10 sub Version {$VERSION}
13 my %Cache; # private cache for all SelfLoader's client packages
15 # allow checking for valid ': attrlist' attachments
24 (?<nested> \( (?: [^()]++ | (?&nested)++ )*+ \) ) ?
26 (?: \s* : \s* | \s+ (?! :) )
30 # in croak and carp, protect $@ from "require Carp;" RT #40216
32 sub croak { { local $@; require Carp; } goto &Carp::croak }
33 sub carp { { local $@; require Carp; } goto &Carp::carp }
37 print STDERR "SelfLoader::AUTOLOAD for $AUTOLOAD\n" if DEBUG;
38 my $SL_code = $Cache{$AUTOLOAD};
39 my $save = $@; # evals in both AUTOLOAD and _load_stubs can corrupt $@
41 # Maybe this pack had stubs before __DATA__, and never initialized.
42 # Or, this maybe an automatic DESTROY method call when none exists.
43 $AUTOLOAD =~ m/^(.*)::/;
44 SelfLoader->_load_stubs($1) unless exists $Cache{"${1}::<DATA"};
45 $SL_code = $Cache{$AUTOLOAD};
46 $SL_code = "sub $AUTOLOAD { }"
47 if (!$SL_code and $AUTOLOAD =~ m/::DESTROY$/);
48 croak "Undefined subroutine $AUTOLOAD" unless $SL_code;
50 print STDERR "SelfLoader::AUTOLOAD eval: $SL_code\n" if DEBUG;
61 defined(&$AUTOLOAD) || die "SelfLoader inconsistency error";
62 delete $Cache{$AUTOLOAD};
66 sub load_stubs { shift->_load_stubs((caller)[0]) }
69 # $endlines is used by Devel::SelfStubber to capture lines after __END__
70 my($self, $callpack, $endlines) = @_;
72 my $fh = \*{"${callpack}::DATA"};
74 my $currpack = $callpack;
75 my($line,$name,@lines, @stubs, $protoype);
77 print STDERR "SelfLoader::load_stubs($callpack)\n" if DEBUG;
78 croak("$callpack doesn't contain an __DATA__ token")
79 unless defined fileno($fh);
80 # Protect: fork() shares the file pointer between the parent and the kid
81 if(sysseek($fh, tell($fh), 0)) {
82 open my $nfh, '<&', $fh or croak "reopen: $!";# dup() the fd
83 close $fh or die "close: $1"; # autocloses, but be paranoid
84 open $fh, '<&', $nfh or croak "reopen2: $!"; # dup() the fd "back"
85 close $nfh or die "close after reopen: $1"; # autocloses, but be paranoid
87 $Cache{"${currpack}::<DATA"} = 1; # indicate package is cached
90 while(defined($line = <$fh>) and $line !~ m/^__END__/) {
91 if ($line =~ m/^sub\s+([\w:]+)\s*((?:\([\\\$\@\%\&\*\;]*\))?(?:$attr_list)?)/) {
92 push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
95 if (index($1,'::') == -1) { # simple sub name
96 $name = "${currpack}::$1";
97 } else { # sub name with package
100 if (defined(&{"${1}::AUTOLOAD"})) {
101 \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
102 die 'SelfLoader Error: attempt to specify Selfloading',
103 " sub $name in non-selfloading module $1";
105 $self->export($1,'AUTOLOAD');
108 } elsif ($line =~ m/^package\s+([\w:]+)/) { # A package declared
109 push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
110 $self->_package_defined($line);
114 $Cache{"${currpack}::<DATA"} = 1; # indicate package is cached
115 if (defined(&{"${1}::AUTOLOAD"})) {
116 \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
117 die 'SelfLoader Error: attempt to specify Selfloading',
118 " package $currpack which already has AUTOLOAD";
120 $self->export($currpack,'AUTOLOAD');
126 if (defined($line) && $line =~ /^__END__/) { # __END__
127 unless ($line =~ /^__END__\s*DATA/) {
129 # Devel::SelfStubber would like us to capture the lines after
130 # __END__ so it can write out the entire file
136 push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
138 eval join('', @stubs) if @stubs;
143 my($self,$fullname,$pack,$lines, $protoype) = @_;
144 return () unless $fullname;
145 carp("Redefining sub $fullname")
146 if exists $Cache{$fullname};
147 $Cache{$fullname} = join('', "package $pack; ",@$lines);
148 print STDERR "SelfLoader cached $fullname: $Cache{$fullname}" if DEBUG;
149 # return stub to be eval'd
150 defined($protoype) ? "sub $fullname $protoype;" : "sub $fullname;"
153 sub _package_defined {}
160 SelfLoader - load functions only on demand
167 ... (initializing code)
175 This module tells its users that functions in the FOOBAR package are to be
176 autoloaded from after the C<__DATA__> token. See also
177 L<perlsub/"Autoloading">.
179 =head2 The __DATA__ token
181 The C<__DATA__> token tells the perl compiler that the perl code
182 for compilation is finished. Everything after the C<__DATA__> token
183 is available for reading via the filehandle FOOBAR::DATA,
184 where FOOBAR is the name of the current package when the C<__DATA__>
185 token is reached. This works just the same as C<__END__> does in
186 package 'main', but for other modules data after C<__END__> is not
187 automatically retrievable, whereas data after C<__DATA__> is.
188 The C<__DATA__> token is not recognized in versions of perl prior to
191 Note that it is possible to have C<__DATA__> tokens in the same package
192 in multiple files, and that the last C<__DATA__> token in a given
193 package that is encountered by the compiler is the one accessible
194 by the filehandle. This also applies to C<__END__> and main, i.e. if
195 the 'main' program has an C<__END__>, but a module 'require'd (_not_ 'use'd)
196 by that program has a 'package main;' declaration followed by an 'C<__DATA__>',
197 then the C<DATA> filehandle is set to access the data after the C<__DATA__>
198 in the module, _not_ the data after the C<__END__> token in the 'main'
199 program, since the compiler encounters the 'require'd file later.
201 =head2 SelfLoader autoloading
203 The B<SelfLoader> works by the user placing the C<__DATA__>
204 token I<after> perl code which needs to be compiled and
205 run at 'require' time, but I<before> subroutine declarations
206 that can be loaded in later - usually because they may never
209 The B<SelfLoader> will read from the FOOBAR::DATA filehandle to
210 load in the data after C<__DATA__>, and load in any subroutine
211 when it is called. The costs are the one-time parsing of the
212 data after C<__DATA__>, and a load delay for the _first_
213 call of any autoloaded function. The benefits (hopefully)
214 are a speeded up compilation phase, with no need to load
215 functions which are never used.
217 The B<SelfLoader> will stop reading from C<__DATA__> if
218 it encounters the C<__END__> token - just as you would expect.
219 If the C<__END__> token is present, and is followed by the
220 token DATA, then the B<SelfLoader> leaves the FOOBAR::DATA
221 filehandle open on the line after that token.
223 The B<SelfLoader> exports the C<AUTOLOAD> subroutine to the
224 package using the B<SelfLoader>, and this loads the called
225 subroutine when it is first called.
227 There is no advantage to putting subroutines which will _always_
228 be called after the C<__DATA__> token.
230 =head2 Autoloading and package lexicals
232 A 'my $pack_lexical' statement makes the variable $pack_lexical
233 local _only_ to the file up to the C<__DATA__> token. Subroutines
234 declared elsewhere _cannot_ see these types of variables,
235 just as if you declared subroutines in the package but in another
236 file, they cannot see these variables.
238 So specifically, autoloaded functions cannot see package
239 lexicals (this applies to both the B<SelfLoader> and the Autoloader).
240 The C<vars> pragma provides an alternative to defining package-level
241 globals that will be visible to autoloaded routines. See the documentation
242 on B<vars> in the pragma section of L<perlmod>.
244 =head2 SelfLoader and AutoLoader
246 The B<SelfLoader> can replace the AutoLoader - just change 'use AutoLoader'
247 to 'use SelfLoader' (though note that the B<SelfLoader> exports
248 the AUTOLOAD function - but if you have your own AUTOLOAD and
249 are using the AutoLoader too, you probably know what you're doing),
250 and the C<__END__> token to C<__DATA__>. You will need perl version 5.001m
251 or later to use this (version 5.001 with all patches up to patch m).
253 There is no need to inherit from the B<SelfLoader>.
255 The B<SelfLoader> works similarly to the AutoLoader, but picks up the
256 subs from after the C<__DATA__> instead of in the 'lib/auto' directory.
257 There is a maintenance gain in not needing to run AutoSplit on the module
258 at installation, and a runtime gain in not needing to keep opening and
259 closing files to load subs. There is a runtime loss in needing
260 to parse the code after the C<__DATA__>. Details of the B<AutoLoader> and
261 another view of these distinctions can be found in that module's
264 =head2 __DATA__, __END__, and the FOOBAR::DATA filehandle.
266 This section is only relevant if you want to use
267 the C<FOOBAR::DATA> together with the B<SelfLoader>.
269 Data after the C<__DATA__> token in a module is read using the
270 FOOBAR::DATA filehandle. C<__END__> can still be used to denote the end
271 of the C<__DATA__> section if followed by the token DATA - this is supported
272 by the B<SelfLoader>. The C<FOOBAR::DATA> filehandle is left open if an
273 C<__END__> followed by a DATA is found, with the filehandle positioned at
274 the start of the line after the C<__END__> token. If no C<__END__> token is
275 present, or an C<__END__> token with no DATA token on the same line, then
276 the filehandle is closed.
278 The B<SelfLoader> reads from wherever the current
279 position of the C<FOOBAR::DATA> filehandle is, until the
280 EOF or C<__END__>. This means that if you want to use
281 that filehandle (and ONLY if you want to), you should either
283 1. Put all your subroutine declarations immediately after
284 the C<__DATA__> token and put your own data after those
285 declarations, using the C<__END__> token to mark the end
286 of subroutine declarations. You must also ensure that the B<SelfLoader>
287 reads first by calling 'SelfLoader-E<gt>load_stubs();', or by using a
288 function which is selfloaded;
292 2. You should read the C<FOOBAR::DATA> filehandle first, leaving
293 the handle open and positioned at the first line of subroutine
296 You could conceivably do both.
298 =head2 Classes and inherited methods.
300 For modules which are not classes, this section is not relevant.
301 This section is only relevant if you have methods which could
304 A subroutine stub (or forward declaration) looks like
308 i.e. it is a subroutine declaration without the body of the
309 subroutine. For modules which are not classes, there is no real
310 need for stubs as far as autoloading is concerned.
312 For modules which ARE classes, and need to handle inherited methods,
313 stubs are needed to ensure that the method inheritance mechanism works
314 properly. You can load the stubs into the module at 'require' time, by
315 adding the statement 'SelfLoader-E<gt>load_stubs();' to the module to do
318 The alternative is to put the stubs in before the C<__DATA__> token BEFORE
319 releasing the module, and for this purpose the C<Devel::SelfStubber>
320 module is available. However this does require the extra step of ensuring
321 that the stubs are in the module. If this is done I strongly recommend
322 that this is done BEFORE releasing the module - it should NOT be done
323 at install time in general.
325 =head1 Multiple packages and fully qualified subroutine names
327 Subroutines in multiple packages within the same file are supported - but you
328 should note that this requires exporting the C<SelfLoader::AUTOLOAD> to
329 every package which requires it. This is done automatically by the
330 B<SelfLoader> when it first loads the subs into the cache, but you should
331 really specify it in the initialization before the C<__DATA__> by putting
332 a 'use SelfLoader' statement in each package.
334 Fully qualified subroutine names are also supported. For example,
341 will all be loaded correctly by the B<SelfLoader>, and the B<SelfLoader>
342 will ensure that the packages 'foo' and 'baz' correctly have the
343 B<SelfLoader> C<AUTOLOAD> method when the data after C<__DATA__> is first