Path: usenet.cis.ufl.edu!usenet.eel.ufl.edu!gatech!news.mathworks.com!europa.chnt.gtegsc.com!news.sprintlink.net!psgrain!nntp.teleport.com!usenet
From: [email protected] ( BIU)
Newsgroups: comp.lang.perl.announce,comp.lang.perl.misc,comp.lang.perl
Subject: SelfLoader (requires 5.001m)
Followup-To: comp.lang.perl.misc
Date: 3 Jul 1995 18:43:16 GMT
Organization: Imperial Cancer Research Fund
Lines: 178
Approved: [email protected] (comp.lang.perl.announce)
Message-ID: <[email protected]>
NNTP-Posting-Host: linda.teleport.com
X-Disclaimer: The "Approved" header verifies header information for article transmission and does not imply approval of content.
Xref: usenet.cis.ufl.edu comp.lang.perl.announce:67 comp.lang.perl.misc:1250 comp.lang.perl:53484

The SelfLoader module is an alternative to the AutoLoader.
You need perl5.001m or later to use it.
Its short enough that I'll include it here.

package SelfLoader;
use Carp;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(AUTOLOAD);
$VERSION = 1.03; sub Version {$VERSION}
$DEBUG = 0;

my %Cache;      # private cache for all SelfLoader's client packages

AUTOLOAD {
   print STDERR "SelfLoader::AUTOLOAD for $AUTOLOAD\n" if $DEBUG;
   my $code = $Cache{$AUTOLOAD};
   unless ($code) {
       # Maybe this pack had stubs before __DATA__, and never initialized.
       # Or, this maybe an automatic DESTROY method call when none exists.
       $AUTOLOAD =~ m/^(.*)::/;
       SelfLoader->_load_stubs($1) unless exists $Cache{"${1}::<DATA"};
       $code = $Cache{$AUTOLOAD};
       $code = "sub $AUTOLOAD { }" if (!$code and $AUTOLOAD =~ m/::DESTROY$/);
       croak "Undefined subroutine $AUTOLOAD" unless $code;
   }
   print STDERR "SelfLoader::AUTOLOAD eval: $code\n" if $DEBUG;
   eval $code;
   if ($@) {
       $@ =~ s/ at .*\n//;
       croak $@;
   }
   defined(&$AUTOLOAD) || die "SelfLoader inconsistency error";
   delete $Cache{$AUTOLOAD};
   goto &$AUTOLOAD
}

sub load_stubs { shift->_load_stubs((caller)[0]) }

sub _load_stubs {
   my($self, $callpack) = @_;
   my $fh = \*{"${callpack}::DATA"};
   my $currpack = $callpack;
   my($line,$name,@lines, @stubs);

   print STDERR "SelfLoader::load_stubs($callpack)\n" if $DEBUG;
   croak("$callpack doesn't contain an __DATA__ token")
       unless fileno($fh);
   $Cache{"${currpack}::<DATA"} = 1;   # indicate package is cached

   while($line = <$fh> and $line !~ m/^__END__/) {
       if ($line =~ m/^sub\s+([\w:]+)/) {      # A sub declared
           push(@stubs, $self->_add_to_cache($name, $currpack, \@lines));
           @lines = ($line);
           if (index($1,'::') == -1) {         # simple sub name
               $name = "${currpack}::$1";
           } else {                            # sub name with package
               $name = $1;
               $name =~ m/^(.*)::/;
               if (defined(&{"${1}::AUTOLOAD"})) {
                   \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
                       die 'SelfLoader Error: attempt to specify Selfloading',
                           " sub $name in non-selfloading module $1";
               } else {
                   $self->export($1,'AUTOLOAD');
               }
           }
       } elsif ($line =~ m/^package\s+([\w:]+)/) { # A package declared
           push(@stubs, $self->_add_to_cache($name, $currpack, \@lines));
           $self->_package_defined($line);
           $name = '';
           @lines = ();
           $currpack = $1;
           $Cache{"${currpack}::<DATA"} = 1;   # indicate package is cached
           if (defined(&{"${1}::AUTOLOAD"})) {
               \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
                   die 'SelfLoader Error: attempt to specify Selfloading',
                       " package $currpack which already has AUTOLOAD";
           } else {
               $self->export($currpack,'AUTOLOAD');
           }
       } else {
           push(@lines,$line);
       }
   }
   close($fh) unless $line;    # __END__
   push(@stubs, $self->_add_to_cache($name, $currpack, \@lines));
   eval join('', @stubs) if @stubs;
}


sub _add_to_cache {
   my($self,$fullname,$pack,$lines) = @_;
   return () unless $fullname;
   carp("Redefining sub $fullname") if exists $Cache{$fullname};
   $Cache{$fullname} = join('', "package $pack; ",@$lines);
   print STDERR "SelfLoader cached $fullname: $Cache{$fullname}" if $DEBUG;
   "sub $fullname;"    # return stub to be eval'd
}

sub _package_defined {}

1;
__END__
=head1 NAME

SelfLoader - load functions only on demand

=head1 SYNOPSIS

   package FOOBAR;
   use SelfLoader;

   ... (initializing code)

   __DATA__
   sub {....


=head1 DESCRIPTION

This module tells its users that functions in the FOOBAR package are to be
autoloaded from after the __DATA__ token.  See also L<perlsub/"Autoloading">.

The SelfLoader can replace the AutoLoader - just change 'use AutoLoader'
to 'use SelfLoader' (though note that the SelfLoader
exports the AUTOLOAD function - but if you have your own AUTOLOAD and
are using the AutoLoader too, you probably know what you're doing),
and the __END__ token to __DATA__. You will need perl version 5.001m
or later to use this (version 5.001 with all patches up to patch m).

There is no need to inherit from the SelfLoader.

Data after the __DATA__ token in a module is read using the
MODULE::DATA filehandle. __END__ can still be used to denote the end
of the __DATA__ section - this is supported by the SelfLoader and
SelfStubber. The MODULE::DATA filehandle is left open if an __END__
is found, with the filehandle positioned at the start of the line after
the __END__ token. If no __END__ token is present, the filehandle is
closed.  But note that the SelfLoader assumes that it is the first to
use that filehandle, so if you want to read after the __END__ you should
ensure that the SelfLoader has had first dibs by either
calling 'SelfLoader->load_stubs();', or by using a function which is
selfloaded.

For modules which are not classes, there is no real need for stubs. This
works the same as the AutoLoader, but picks up the subs from after
the __DATA__ instead of in the 'lib/auto' directory. There is a significant
gain in not needing to run AutoSplit on the module at installation, and
not needing to keep opening and closing files to load subs.

For modules which ARE classes, and need to handle inherited methods,
stubs are needed to ensure that the method inheritance mechanism works
properly. You can load the stubs into the module at 'require' time, by
adding the statement 'SelfLoader->load_stubs();' to the module to do
this.

The alternative is to put the stubs in before the __DATA__ token BEFORE
releasing the module, and for this purpose the Devel::SelfStubber
module is available.  However this does require the extra step of ensuring
that the stubs are in the module. If this is done I strongly recommend
that this is done BEFORE releasing the module - it should NOT be done
at install time in general.

Subs in multiple packages within the same file are supported - but you
should note that this requires exporting the SelfLoader::AUTOLOAD to
every package which requires it. This is done automatically by the
SelfLoader when it first loads the subs into the cache, but you should
really specify it in the initialization before the __DATA__ by putting
a 'use SelfLoader' statement in each package.

=cut
--
      Jack               [email protected]

If you only have a hammer, you tend to see every problem as a nail.
               -- Maslow