Modern Perl 2011-2012 by Unknown

Modern Perl 2011-2012 by Unknown

Author:Unknown
Language: eng
Format: epub


Modern Perl

package Proxy::Log;

sub new

{

my ($class, $proxied) = @_;

bless \$proxied, $class;

}

sub AUTOLOAD

{

my ($name) = our $AUTOLOAD =~ /::(\w+)$/;

Log::method_call( $name, @_ );

my $self = shift;

return $$self->$name( @_ );

}

This AUTOLOAD() logs the method call. Then it dereferences the proxied object from a blessed scalar reference, extracts the

name of the undefined method, then invokes that method on the proxied object with the provided parameters.

Generating Code in AUTOLOAD()

This double dispatch is easy to write but inefficient. Every method call on the proxy must fail normal dispatch to end up in

AUTOLOAD(). Pay that penalty only once by installing new methods into the proxy class as the program needs them:

sub AUTOLOAD

{

my ($name) = our $AUTOLOAD =~ /::(\w+)$/;

my $method = sub

{

Log::method_call( $name, @_ );

my $self = shift;

return $$self->$name( @_ );

}

no strict 'refs';

*{ $AUTOLOAD } = $method;

return $method->( @_ );

}

The body of the previous AUTOLOAD() has become a closure (Closures, pp. 86) bound over the name of the undefined method.

Installing that closure in the appropriate symbol table allows all subsequent dispatch to that method to find the created closure

(and avoid AUTOLOAD()). This code finally invokes the method directly and returns the result.

Though this approach is cleaner and almost always more transparent than handling the behavior directly in AUTOLOAD(), the

code called by AUTOLOAD() may detect that dispatch has gone through AUTOLOAD(). In short, caller() will reflect the

double-dispatch of both techniques shown so far. While it may violate encapsulation to care that this occurs, leaking the details

of how an object provides a method may also violate encapsulation.

Some code uses a tailcall (Tailcalls, pp. 38) to replace the current invocation of AUTOLOAD() with a call to the destination method:

sub AUTOLOAD

{

94



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.