[prog] Perl decorator classes

Wolfgang Petzold petzold at villa-chaos.de
Mon Jun 23 15:00:00 EST 2003


Dan Richter, 23.06.03:

> However, LWP::UserAgent is quite complex and implements a large number of
> methods, and it would be a pain to type "sub foo { my $self=shift; return
> $self->ua->foo(@_); }" for every single method. Is there some way of
> importing the package and copying all the functions, with my slightly
> modified definitions?

I've done a quite similar thing using the AUTOLOAD method. For every
method call that is not defined in a package AUTOLOAD is called. So, you
could do something like:

---------------------------------------------------------------------
package MySmartPackage;
# [...]

sub AUTOLOAD {
	my $self = shift;
	my $requested_method = $MySmartPackage::AUTOLOAD;

	# strip off leading stuff from method name
	#
	$requested_method =~ s/.*://;

	###
	### check here if this requested method that is unknown to
	### MySmartPackage is to be called using LWP::UserAgent,
	### or if you want to throw the call away, or... whatever.
	###

	# finally call the function from LWP::UserAgent
	# (using the syntax that you suggested in your question)
	#
	return $self->ua->$requested_method(@_);
}
---------------------------------------------------------------------

Another possibility might be subclassing LWP::UserAgent and changing
methods you want to be different and/or adding others.


Wolfgang



More information about the Programming mailing list