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)];
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.