Paul Johnson wrote:
On Sat, Oct 23, 2010 at 07:52:50PM +0200, Shlomi Fish wrote:
On Saturday 23 October 2010 18:50:44 David Favor wrote:
Given an instantiated class object, what's the
best way to add additional methods after instantiation.
Specifically I'm working with qpsmtpd and desire to
add a method is_spooled() to every session, so I can
call if ($self->is_spooled) rather then is_spooled($self)...
Maybe try Class::MOP's add_method:
http://search.cpan.org/perldoc?Class::MOP::Class
There are closer-to-the-metal ways but they are probably less recommended.
Or perhaps more recommended:
package A;
sub a { print "a" }
package B;
sub A::b { shift->a; print "b" }
(bless {}, "A")->b;
Just be sure you know what you are doing. Adding a method to somone else's
class can be considered rude. See the NOTE in perldoc perlmodlib.
sub add_class_method {
my($class,$name,$code) = @_;
no strict 'refs';
${$class . '::'}{$name} = $code;
}
sub somewhere_in_da_code {
... ... ...
my $class = 'Qpsmtpd::Transaction';
my $name = 'test_method';
my $code = \&test_method;
add_class_method($class,$name,$code);
# all three of these invocations works correctly
test_method($self);
&$code($self);
$self->test_method;
}
--
Love feeling your best ever, all day, every day?
Click http://RadicalHealth.com for the easy way!
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/