Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: on the fly methods

by Rhandom (Curate)
on Feb 27, 2007 at 16:47 UTC ( [id://602334]=note: print w/replies, xml ) Need Help??


in reply to on the fly methods

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)];

Replies are listed 'Best First'.
Re^2: on the fly methods
by chromatic (Archbishop) on Feb 27, 2007 at 18:50 UTC

    You just broke overloading:

    # (! Scalar::Util::reftype($code) ne 'CODE') { if (! UNIVERSAL::isa($code, 'CODE')) {

    How about:

    unless (defined &$code) {

    Also, isa() is a method, not a function. Using it as a function can break many things.

      Sorry to the original thread as we are now a bit off the beaten topic.

      Yes. It is a method. It will skip $code's ->isa. It breaks overloading. It also works in 99% of the use cases (probably more) that the general programming population will use and in those cases where somebody has created an object that pretends to be code they can simply pass sub { &$code } and suddenly it works fine. Changing to $code->isa('CODE') in this case would actually break 99% of use cases because it only allows for objects that are CODE (not bare coderefs). I think it is wonderful that Perl 5 (and other languages) can call methods in a more functional form if the need arises.

      Using defined &$code almost works but it breaks if a non-coderef reference is passed in. It also doesn't go the full route of supporting overloaded objects so it isn't any more of a solution.
      The only thing that "might" be able to handle 100% of cases is something like
      use Scalar::Util qw(blessed); my $is_code = blessed($code) ? $code->can('&{}') : ref($code) eq 'CODE +';

      UPDATE: - Yup - I missed blessed coderefs which would have to be checked for with eval { defined &$code }. The corrected code might look like
      my $is_code = ! blessed($code) ? ref($code) eq 'CODE' : $code->can('&{}') || $code->isa('CODE') # arguably not a good test (bless +{}, 'CODE') || eval { defined &$code }; # arguably bad because it ge +ts called in some contexts


      Arguably that isn't all that bad. I'm sure there is probably still a case I'm missing. I do know of a few companies that are still pre-Perl 5.8 and the Scalar::Util::blessed route isn't even an option for them.

      Yes. I agree that things can break. Perl 5 has problems in being able to type data or easily (s/easily/succinctly/) detect the type or capabilities of data. There are many things that can break during argument passing in Perl 5. There are basic things that can be done to check for basic types of data. If advanced users want to pass in advanced types, the basic checks won't prohibit them - they just force them to wrap them in more palatable forms. Although many times the "basic" checks I've seen are indeed poorly done and restrict viable options that would otherwise work just fine.

      I've probably already gone too far. There are many who feel very strongly about this issue. But the picture painted is usually more severe that is necessary and when presented as a blanket statement hides useful, working use cases.

      Often on Perlmonks there is the assumption that one doesn't know what they are doing when they actually do. And of course there are those that assume they know what they are doing when they actually do not.

      my @a=qw(random brilliant braindead); print $a[rand(@a)];
        Changing to $code->isa('CODE') in this case would actually break 99% of use cases...

        So would changing to fileno $code, but I didn't suggest that either.

        I don't really care if the naive approach satisfies 99% of the use cases for two reasons. First, I've had well-used code on the CPAN for years that tends to break in messy ways when people use quick hacks instead of well-tested, working code. Second, plenty of people pick up on bad idioms and use them without realizing where they fail and what they break. This leads to even more people breaking my code. and complaining to me and I just can't fix the problems.

        I'd love to see a test case for when eval { defined &$code } fails. I couldn't come up with one. I even tried it with overloaded objects.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://602334]
help
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found