Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: A Better way? (Lots of routines with similar structure)

by zengargoyle (Deacon)
on Jun 08, 2003 at 21:12 UTC ( [id://264163]=note: print w/replies, xml ) Need Help??


in reply to A Better way? (Lots of routines with similar structure)

to start, try using the magic of AUTOLOAD

#!/usr/bin/perl use strict; use warnings; package Thing; use Quantum::Superpositions; sub new { my ($class,$txt) = @_; return bless \$txt, $class; } sub txt { my ($self) = @_; return $$self; } my @allowed = qw[ findActor addActor findMovie addMovie ]; sub AUTOLOAD { my ($self, @args) = @_; use vars '$AUTOLOAD'; (my $funcname = $AUTOLOAD) =~ s/.*:://; unless ($funcname eq any(@allowed)) { die "don't know how to $funcname on ", $self->txt, $/; } warn "doing $funcname on ", $self->txt, " with @args$/"; } sub DESTROY { } # for AUTOLOAD happiness 1; package main; my $b = Thing->new("bob"); my $c = Thing->new("ralph"); $b->findActor("quincy"); $c->addActor("mary"); $b->doActor("what?"); __END__ doing findActor on bob with quincy doing addActor on ralph with mary don't know how to doActor on bob

later down the line you can loop through your supported functions and create anonymous sub's and attach them directly to your package namespace with GLOB magic.

package Thing2; sub new { my ($class,$txt) = @_; return bless \$txt, $class; } sub txt { my ($self) = @_; return $$self; } my @allowed = qw[ findActor addActor findMovie addMovie ]; foreach my $funcname (@allowed) { my $sub = sub { my ($self, @args) = @_; warn "doing $funcname on ", $self->txt, " with @args$/"; }; my $pkgfunc = __PACKAGE__ . "::$funcname"; no strict 'refs'; *$pkgfunc = $sub; } 1; package main; my $b = Thing2->new("bob"); my $c = Thing2->new("ralph"); $b->findActor("quincy"); $c->addActor("mary"); $b->doActor("what?"); __END__ doing findActor on bob with quincy doing addActor on ralph with mary Can't locate object method "doActor" via package "Thing2" (perhaps you + forgot to load "Thing2"?) at ./qs.pl line 76.

Replies are listed 'Best First'.
Re: Re: A Better way? (Lots of routines with similar structure)
by Ryszard (Priest) on Aug 11, 2003 at 19:09 UTC
    This is absolutely the thing i was after, thanks ++.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://264163]
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: (7)
As of 2024-03-28 19:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found