Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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)];

In reply to Re: on the fly methods by Rhandom
in thread on the fly methods by Ojosh!ro

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-19 12:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found