There are various ways. The least dirty is to use the AUTOLOAD system as in the following.
package Foo;
use strict;
use vars qw($AUTOLOAD);
use Carp qw(croak);
sub new { bless {}, __PACKAGE__ }
sub add_method {
my ($self, $name, $code) = @_;
### This following chunk could use Scalar::Util::blessed
### if they have perl 5.8 installed. We will operate without it
if (! ref $code) {
# scary and sort of ugly but thats what the OP wanted
$code = eval $code;
}
# (! Scalar::Util::reftype($code) ne 'CODE') {
if (! UNIVERSAL::isa($code, 'CODE')) {
croak "Usage : add_method(method => sub {})\n
add_method(method => 'sub {}')";
}
$self->{'_methods'}->{$name} = $code;
}
sub AUTOLOAD {
my $self = shift;
my $name = $AUTOLOAD =~ /(\w+)$/ ? $1 : croak "Invalid method \"$A
+UTOLOAD\"";
my $code = $self->{'_methods'}->{$name}
|| croak "No such method \"$name\" via package ".__PACKAGE__;
$self->$code(@_);
}
my $foo = Foo->new;
$foo->add_method(bar => sub { print "bar\n" });
$foo->add_method(baz => 'sub { print "baz\n" }');
$foo->bar;
$foo->baz;
The other way of doing this sort of thing involves manipulating the symbol table which isn't hard, but I wouldn't recommend if you are just starting out.
my @a=qw(random brilliant braindead); print $a[rand(@a)];
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|