1package AutoLoader;
2
3use strict;
4use 5.006_001;
5
6our($VERSION, $AUTOLOAD);
7
8my $is_dosish;
9my $is_epoc;
10my $is_vms;
11my $is_macos;
12
13BEGIN {
14    $is_dosish = $^O eq 'dos' || $^O eq 'os2' || $^O eq 'MSWin32' || $^O eq 'NetWare';
15    $is_epoc = $^O eq 'epoc';
16    $is_vms = $^O eq 'VMS';
17    $is_macos = $^O eq 'MacOS';
18    $VERSION = '5.60';
19}
20
21AUTOLOAD {
22    my $sub = $AUTOLOAD;
23    my $filename;
24    # Braces used to preserve $1 et al.
25    {
26	# Try to find the autoloaded file from the package-qualified
27	# name of the sub. e.g., if the sub needed is
28	# Getopt::Long::GetOptions(), then $INC{Getopt/Long.pm} is
29	# something like '/usr/lib/perl5/Getopt/Long.pm', and the
30	# autoload file is '/usr/lib/perl5/auto/Getopt/Long/GetOptions.al'.
31	#
32	# However, if @INC is a relative path, this might not work.  If,
33	# for example, @INC = ('lib'), then $INC{Getopt/Long.pm} is
34	# 'lib/Getopt/Long.pm', and we want to require
35	# 'auto/Getopt/Long/GetOptions.al' (without the leading 'lib').
36	# In this case, we simple prepend the 'auto/' and let the
37	# C<require> take care of the searching for us.
38
39	my ($pkg,$func) = ($sub =~ /(.*)::([^:]+)$/);
40	$pkg =~ s#::#/#g;
41	if (defined($filename = $INC{"$pkg.pm"})) {
42	    if ($is_macos) {
43		$pkg =~ tr#/#:#;
44		$filename = undef
45		  unless $filename =~ s#^(.*)$pkg\.pm\z#$1auto:$pkg:$func.al#s;
46	    } else {
47		$filename = undef
48		  unless $filename =~ s#^(.*)$pkg\.pm\z#$1auto/$pkg/$func.al#s;
49	    }
50
51	    # if the file exists, then make sure that it is a
52	    # a fully anchored path (i.e either '/usr/lib/auto/foo/bar.al',
53	    # or './lib/auto/foo/bar.al'.  This avoids C<require> searching
54	    # (and failing) to find the 'lib/auto/foo/bar.al' because it
55	    # looked for 'lib/lib/auto/foo/bar.al', given @INC = ('lib').
56
57	    if (defined $filename and -r $filename) {
58		unless ($filename =~ m|^/|s) {
59		    if ($is_dosish) {
60			unless ($filename =~ m{^([a-z]:)?[\\/]}is) {
61			     if ($^O ne 'NetWare') {
62					$filename = "./$filename";
63				} else {
64					$filename = "$filename";
65				}
66			}
67		    }
68		    elsif ($is_epoc) {
69			unless ($filename =~ m{^([a-z?]:)?[\\/]}is) {
70			     $filename = "./$filename";
71			}
72		    }
73		    elsif ($is_vms) {
74			# XXX todo by VMSmiths
75			$filename = "./$filename";
76		    }
77		    elsif (!$is_macos) {
78			$filename = "./$filename";
79		    }
80		}
81	    }
82	    else {
83		$filename = undef;
84	    }
85	}
86	unless (defined $filename) {
87	    # let C<require> do the searching
88	    $filename = "auto/$sub.al";
89	    $filename =~ s#::#/#g;
90	}
91    }
92    my $save = $@;
93    local $!; # Do not munge the value.
94    eval { local $SIG{__DIE__}; require $filename };
95    if ($@) {
96	if (substr($sub,-9) eq '::DESTROY') {
97	    no strict 'refs';
98	    *$sub = sub {};
99	    $@ = undef;
100	} elsif ($@ =~ /^Can't locate/) {
101	    # The load might just have failed because the filename was too
102	    # long for some old SVR3 systems which treat long names as errors.
103	    # If we can successfully truncate a long name then it's worth a go.
104	    # There is a slight risk that we could pick up the wrong file here
105	    # but autosplit should have warned about that when splitting.
106	    if ($filename =~ s/(\w{12,})\.al$/substr($1,0,11).".al"/e){
107		eval { local $SIG{__DIE__}; require $filename };
108	    }
109	}
110	if ($@){
111	    $@ =~ s/ at .*\n//;
112	    my $error = $@;
113	    require Carp;
114	    Carp::croak($error);
115	}
116    }
117    $@ = $save;
118    goto &$sub;
119}
120
121sub import {
122    my $pkg = shift;
123    my $callpkg = caller;
124
125    #
126    # Export symbols, but not by accident of inheritance.
127    #
128
129    if ($pkg eq 'AutoLoader') {
130	no strict 'refs';
131	*{ $callpkg . '::AUTOLOAD' } = \&AUTOLOAD
132	    if @_ and $_[0] =~ /^&?AUTOLOAD$/;
133    }
134
135    #
136    # Try to find the autosplit index file.  Eg., if the call package
137    # is POSIX, then $INC{POSIX.pm} is something like
138    # '/usr/local/lib/perl5/POSIX.pm', and the autosplit index file is in
139    # '/usr/local/lib/perl5/auto/POSIX/autosplit.ix', so we require that.
140    #
141    # However, if @INC is a relative path, this might not work.  If,
142    # for example, @INC = ('lib'), then
143    # $INC{POSIX.pm} is 'lib/POSIX.pm', and we want to require
144    # 'auto/POSIX/autosplit.ix' (without the leading 'lib').
145    #
146
147    (my $calldir = $callpkg) =~ s#::#/#g;
148    my $path = $INC{$calldir . '.pm'};
149    if (defined($path)) {
150	# Try absolute path name.
151	if ($is_macos) {
152	    (my $malldir = $calldir) =~ tr#/#:#;
153	    $path =~ s#^(.*)$malldir\.pm\z#$1auto:$malldir:autosplit.ix#s;
154	} else {
155	    $path =~ s#^(.*)$calldir\.pm\z#$1auto/$calldir/autosplit.ix#;
156	}
157
158	eval { require $path; };
159	# If that failed, try relative path with normal @INC searching.
160	if ($@) {
161	    $path ="auto/$calldir/autosplit.ix";
162	    eval { require $path; };
163	}
164	if ($@) {
165	    my $error = $@;
166	    require Carp;
167	    Carp::carp($error);
168	}
169    }
170}
171
172sub unimport {
173    my $callpkg = caller;
174
175    no strict 'refs';
176    my $symname = $callpkg . '::AUTOLOAD';
177    undef *{ $symname } if \&{ $symname } == \&AUTOLOAD;
178    *{ $symname } = \&{ $symname };
179}
180
1811;
182
183__END__
184
185=head1 NAME
186
187AutoLoader - load subroutines only on demand
188
189=head1 SYNOPSIS
190
191    package Foo;
192    use AutoLoader 'AUTOLOAD';   # import the default AUTOLOAD subroutine
193
194    package Bar;
195    use AutoLoader;              # don't import AUTOLOAD, define our own
196    sub AUTOLOAD {
197        ...
198        $AutoLoader::AUTOLOAD = "...";
199        goto &AutoLoader::AUTOLOAD;
200    }
201
202=head1 DESCRIPTION
203
204The B<AutoLoader> module works with the B<AutoSplit> module and the
205C<__END__> token to defer the loading of some subroutines until they are
206used rather than loading them all at once.
207
208To use B<AutoLoader>, the author of a module has to place the
209definitions of subroutines to be autoloaded after an C<__END__> token.
210(See L<perldata>.)  The B<AutoSplit> module can then be run manually to
211extract the definitions into individual files F<auto/funcname.al>.
212
213B<AutoLoader> implements an AUTOLOAD subroutine.  When an undefined
214subroutine in is called in a client module of B<AutoLoader>,
215B<AutoLoader>'s AUTOLOAD subroutine attempts to locate the subroutine in a
216file with a name related to the location of the file from which the
217client module was read.  As an example, if F<POSIX.pm> is located in
218F</usr/local/lib/perl5/POSIX.pm>, B<AutoLoader> will look for perl
219subroutines B<POSIX> in F</usr/local/lib/perl5/auto/POSIX/*.al>, where
220the C<.al> file has the same name as the subroutine, sans package.  If
221such a file exists, AUTOLOAD will read and evaluate it,
222thus (presumably) defining the needed subroutine.  AUTOLOAD will then
223C<goto> the newly defined subroutine.
224
225Once this process completes for a given function, it is defined, so
226future calls to the subroutine will bypass the AUTOLOAD mechanism.
227
228=head2 Subroutine Stubs
229
230In order for object method lookup and/or prototype checking to operate
231correctly even when methods have not yet been defined it is necessary to
232"forward declare" each subroutine (as in C<sub NAME;>).  See
233L<perlsub/"SYNOPSIS">.  Such forward declaration creates "subroutine
234stubs", which are place holders with no code.
235
236The AutoSplit and B<AutoLoader> modules automate the creation of forward
237declarations.  The AutoSplit module creates an 'index' file containing
238forward declarations of all the AutoSplit subroutines.  When the
239AutoLoader module is 'use'd it loads these declarations into its callers
240package.
241
242Because of this mechanism it is important that B<AutoLoader> is always
243C<use>d and not C<require>d.
244
245=head2 Using B<AutoLoader>'s AUTOLOAD Subroutine
246
247In order to use B<AutoLoader>'s AUTOLOAD subroutine you I<must>
248explicitly import it:
249
250    use AutoLoader 'AUTOLOAD';
251
252=head2 Overriding B<AutoLoader>'s AUTOLOAD Subroutine
253
254Some modules, mainly extensions, provide their own AUTOLOAD subroutines.
255They typically need to check for some special cases (such as constants)
256and then fallback to B<AutoLoader>'s AUTOLOAD for the rest.
257
258Such modules should I<not> import B<AutoLoader>'s AUTOLOAD subroutine.
259Instead, they should define their own AUTOLOAD subroutines along these
260lines:
261
262    use AutoLoader;
263    use Carp;
264
265    sub AUTOLOAD {
266        my $sub = $AUTOLOAD;
267        (my $constname = $sub) =~ s/.*:://;
268        my $val = constant($constname, @_ ? $_[0] : 0);
269        if ($! != 0) {
270            if ($! =~ /Invalid/ || $!{EINVAL}) {
271                $AutoLoader::AUTOLOAD = $sub;
272                goto &AutoLoader::AUTOLOAD;
273            }
274            else {
275                croak "Your vendor has not defined constant $constname";
276            }
277        }
278        *$sub = sub { $val }; # same as: eval "sub $sub { $val }";
279        goto &$sub;
280    }
281
282If any module's own AUTOLOAD subroutine has no need to fallback to the
283AutoLoader's AUTOLOAD subroutine (because it doesn't have any AutoSplit
284subroutines), then that module should not use B<AutoLoader> at all.
285
286=head2 Package Lexicals
287
288Package lexicals declared with C<my> in the main block of a package
289using B<AutoLoader> will not be visible to auto-loaded subroutines, due to
290the fact that the given scope ends at the C<__END__> marker.  A module
291using such variables as package globals will not work properly under the
292B<AutoLoader>.
293
294The C<vars> pragma (see L<perlmod/"vars">) may be used in such
295situations as an alternative to explicitly qualifying all globals with
296the package namespace.  Variables pre-declared with this pragma will be
297visible to any autoloaded routines (but will not be invisible outside
298the package, unfortunately).
299
300=head2 Not Using AutoLoader
301
302You can stop using AutoLoader by simply
303
304	no AutoLoader;
305
306=head2 B<AutoLoader> vs. B<SelfLoader>
307
308The B<AutoLoader> is similar in purpose to B<SelfLoader>: both delay the
309loading of subroutines.
310
311B<SelfLoader> uses the C<__DATA__> marker rather than C<__END__>.
312While this avoids the use of a hierarchy of disk files and the
313associated open/close for each routine loaded, B<SelfLoader> suffers a
314startup speed disadvantage in the one-time parsing of the lines after
315C<__DATA__>, after which routines are cached.  B<SelfLoader> can also
316handle multiple packages in a file.
317
318B<AutoLoader> only reads code as it is requested, and in many cases
319should be faster, but requires a mechanism like B<AutoSplit> be used to
320create the individual files.  L<ExtUtils::MakeMaker> will invoke
321B<AutoSplit> automatically if B<AutoLoader> is used in a module source
322file.
323
324=head1 CAVEATS
325
326AutoLoaders prior to Perl 5.002 had a slightly different interface.  Any
327old modules which use B<AutoLoader> should be changed to the new calling
328style.  Typically this just means changing a require to a use, adding
329the explicit C<'AUTOLOAD'> import if needed, and removing B<AutoLoader>
330from C<@ISA>.
331
332On systems with restrictions on file name length, the file corresponding
333to a subroutine may have a shorter name that the routine itself.  This
334can lead to conflicting file names.  The I<AutoSplit> package warns of
335these potential conflicts when used to split a module.
336
337AutoLoader may fail to find the autosplit files (or even find the wrong
338ones) in cases where C<@INC> contains relative paths, B<and> the program
339does C<chdir>.
340
341=head1 SEE ALSO
342
343L<SelfLoader> - an autoloader that doesn't use external files.
344
345=cut
346