Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^4: defining methods on the fly

by jdhedden (Deacon)
on Aug 03, 2006 at 19:14 UTC ( [id://565534]=note: print w/replies, xml ) Need Help??


in reply to Re^3: defining methods on the fly
in thread defining methods on the fly

The following modification does not assign to a glob. Do this avoid the cache reset issue?
#!/usr/local/bin/perl use warnings; use strict; use Want; sub lvalueMethod($) { my ($name) = @_; my ($package) = caller; no strict 'refs'; *{$package . "::" . $name} = sub :lvalue { my $self = shift; if (!want('LVALUE') && ref($self->{$name}) eq 'CODE') { goto &{$self->{$name}}; } $self->{$name}; }; } { package Foo; sub new { bless {}, shift; } main::lvalueMethod("bar"); } my ($x) = Foo->new(); print "$x\n"; $x->bar = 5; print $x->bar, "\n"; $x->bar = sub { print( @_, "\n" ); }; $x->bar("Hello World");

Remember: There's always one more bug.

Replies are listed 'Best First'.
Re^5: defining methods on the fly
by flogic (Acolyte) on Aug 03, 2006 at 20:24 UTC
    From my understanding of his response that avoids the issue.
Re^5: defining methods on the fly
by revdiablo (Prior) on Aug 04, 2006 at 17:37 UTC
    The following modification does not assign to a glob.

    Apologies if I'm misunderstanding something here, but isn't the following code assigning to a glob?

    *{$package . "::" . $name} = sub :lvalue {

    Update: Thanks for the reply -- I was indeed "misunderstanding something here."

      Apologies if I'm misunderstanding something here, but isn't the following code assigning to a glob?
      *{$package . "::" . $name} = sub :lvalue {
      True, but that wasn't what I was referring to. The above is only executed once. The concern was with the following line in the original code that was executed every time the method was called:
      local *call = sub { $self->{$name}->(@_); };
      By removing that line, my suggested code should not suffer from the method cache reset performance penalty that occurs each time the method in the original code is called.

      Remember: There's always one more bug.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-04-25 23:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found