Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

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 :)

Replies are listed 'Best First'.
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?

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2023-02-04 02:51 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (30 votes). Check out past polls.