Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Nested Classes

by Tyke (Pilgrim)
on Mar 02, 2001 at 19:19 UTC ( #61806=note: print w/ replies, xml ) Need Help??


in reply to Nested Classes

Well, yes but I'm not quite sure why you'd want to do this.

Is this what you want?

#!perl -w use strict; my $a = 'foo'; my $b = \$a; bless $b, 'bar'; sub bar::f1 { my $self = shift; print "f1 prints [$$self]\n"; } *bar::f2 = sub { my $self = shift; print "f2 prints [$$self]\n"; }; $b->f1(); $b->f2();
Update: Changed PRE tags to CODE tags as per chipmunk's request. Sorry, won't do it again :)


Comment on Re: Nested Classes
Download Code
Re: Re: Nested Classes
by InfiniteSilence (Curate) on Mar 02, 2001 at 20:57 UTC
    Here's a slightly more verbose version of the same thing:
    #!/usr/bin/perl -w use strict; package foo; sub new{ my $m = {}; bless $m; return $m;} package bar; sub new{ my $b = {}; bless $b; return $b;} sub corny { return 'sparky'; } package main; my $s = foo->new(); my $r = bar->new(); $s->{'spark'} = \&bar::corny; print $s->{'spark'}(); 1;
    This essentially calls a method out of a different package. I added the class stuff as window dressing. If you are looking to call and actual method from an instantiated object, just call a function and use a reference to the object as a parameter (called delegation in certain circles) to call the function. Lastly, use inheritance. If these things don't help, I am not sure what you are attempting to accomplish.

    Celebrate Intellectual Diversity

      The OP asked how to
      1. create an object,
      2. bless,
      3. and then bind subroutines to it (written within another objects method) as methods.

      That's what I tried to show. Sure it's better to define classes statically. But as I understood the OP, he wanted to do this on the fly

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2014-10-31 07:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (215 votes), past polls