J Krugman <> wrote in comp.lang.perl.misc:
> In <> Brian McCauley <> writes:
>
> >J Krugman <> writes:
>
> >> I've just come across this sort of code (from the CPAN module
> >> SOAP::Lite):
> >>
> >> sub BEGIN {
> >> no strict 'refs';
> >> for my $method (qw(ids hrefs parts parser base xmlschemas xmlschema)) {
> >> my $field = '_' . $method;
> >> *$method = sub {
> >> my $self = shift->new;
> >> @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
> >> }
> >> }
> >> }
> >>
> >> (SOAP::Lite comprises many packages; practically every one of them
> >> has a BEGIN block in which methods are defined using this technique.)
> >>
> >> This seems to me like an alternative to AUTOLOAD for defining
> >> generic accessor methods. Any ideas about why this technique would
> >> be preferable to using AUTOLOAD?
>
> >If a package can be subclassed then all it's autoloadable methods have
> >to be stubbed so that Perl knows to call the AUTOLOAD in your class
> >not in the subclass.
>
> >The choice beween using stubs and AUTOLOAD or just defining the whole
> >lot in a loop is largely a matter of personal preference.
>
> Pardon my ignorance, but what are stubs? Where can I find
> documentation on this? I couldn't find a definition of "stub" in
> any of the usual places (Programming Perl, perltoot, FAQ, etc.)
It's another name for a "forward" declaration, which looks like
sub foo;
This declares "foo" as a subroutine, but leaves the definition for
later. One way of completing the definition is through AUTOLOADER.
The effect of a forward declaration is that "foo" is known to be
a subroutine from then on. So ...->can( "foo") will find the method
"foo" if it is declared (it doesn't have to be defined). Even
"\ &foo" can be used and will do the right thing if the definition
is supplied later.
Anno
|