Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
This piece of code may serve as the base class for objects that need singleton methods (methods specific for this object and not for whole class). One can use it directly
my $obj = DynObject->new(id => 'MyObj', action => sub{print "hi\n";}); print $obj->id, "\n"; $obj->action();
or as base class
$obj = MyDyn->new(id => 'MyObj'); print $obj->id, "\n"; $obj->action(); package MyDyn; use base 'DynObject'; sub action { print "hi\n"; }
use strict; package DynObject; use Carp; my $counter = 0; sub new { my $class = shift; croak("The number of parameters must be even") unless @_ % 2 == 0; no strict 'refs'; my $type = ref $class; my $code; if(!$type) { $type = __PACKAGE__; $type .= "::obj@{[$counter++]}"; *{"${type}::ISA"} = [$class]; } for(my $i = 0; $i < @_; $i+=2) { croak("The method name '$_[$i]' is not a word") unless $_[$i] =~ /^\w+$/ && $_[$i] !~ /^\d+$/; if(ref $_[$i+1] eq 'CODE') { *{"${type}::$_[$i]"} = $_[$i+1]; } elsif(defined $_[$i+1] && !ref $_[$i+1]) { my $str = $_[$i+1]; *{"${type}::$_[$i]"} = sub{$str}; } else { delete ${"${type}::"}{$_[$i]}; } } return ref $class ? $class : bless [], $type; } sub DESTROY { my $obj = shift; my $type = ref $obj; $type =~ s/(\w+)$//; my $name = $1 . "::"; no strict 'refs'; delete ${$type}{$name}; } 1;

In reply to adding singleton methods to objects by andal

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 about the Monastery: (5)
As of 2024-03-29 10:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found