perl 5.002gamma: lib/Getopt/Long.pm
[p5sagit/p5-mst-13.2.git] / lib / AutoLoader.pm
1 package AutoLoader;
2 use Carp;
3 $DB::sub = $DB::sub;    # Avoid warning
4
5 =head1 NAME
6
7 AutoLoader - load functions only on demand
8
9 =head1 SYNOPSIS
10
11     package FOOBAR;
12     use Exporter;
13     use AutoLoader;
14     @ISA = (Exporter, AutoLoader);
15
16 =head1 DESCRIPTION
17
18 This module tells its users that functions in the FOOBAR package are to be
19 autoloaded from F<auto/$AUTOLOAD.al>.  See L<perlsub/"Autoloading">.
20
21 =cut
22
23 AUTOLOAD {
24     my $name = "auto/$AUTOLOAD.al";
25     $name =~ s#::#/#g;
26     eval {require $name};
27     if ($@) {
28         # The load might just have failed because the filename was too
29         # long for some old SVR3 systems which treat long names as errors.
30         # If we can succesfully truncate a long name then it's worth a go.
31         # There is a slight risk that we could pick up the wrong file here
32         # but autosplit should have warned about that when splitting.
33         if ($name =~ s/(\w{12,})\.al$/substr($1,0,11).".al"/e){
34             eval {require $name};
35         }
36         elsif ($AUTOLOAD =~ /::DESTROY$/) {
37             # eval "sub $AUTOLOAD {}";
38             *$AUTOLOAD = sub {};
39         }
40         if ($@){
41             $@ =~ s/ at .*\n//;
42             croak $@;
43         }
44     }
45     $DB::sub = $AUTOLOAD;       # Now debugger know where we are.
46     goto &$AUTOLOAD;
47 }
48                             
49 sub import {
50     my ($callclass, $callfile, $callline,$path,$callpack) = caller(0);
51     ($callpack = $callclass) =~ s#::#/#;
52     # Try to find the autosplit index file.  Eg., if the call package
53     # is POSIX, then $INC{POSIX.pm} is something like
54     # '/usr/local/lib/perl5/POSIX.pm', and the autosplit index file is in
55     # '/usr/local/lib/perl5/auto/POSIX/autosplit.ix', so we require that.
56     #
57     # However, if @INC is a relative path, this might not work.  If,
58     # for example, @INC = ('lib'), then
59     # $INC{POSIX.pm} is 'lib/POSIX.pm', and we want to require
60     # 'auto/POSIX/autosplit.ix' (without the leading 'lib').
61     #
62     if (defined($path = $INC{$callpack . '.pm'})) {
63         # Try absolute path name.
64         $path =~ s#^(.*)$callpack\.pm$#$1auto/$callpack/autosplit.ix#;
65         eval { require $path; };
66         # If that failed, try relative path with normal @INC searching.
67         if ($@) {
68             $path ="auto/$callpack/autosplit.ix";
69             eval { require $path; };
70         }
71         carp $@ if ($@);  
72     } 
73 }
74
75 1;