ignatz has asked for the wisdom of the Perl Monks concerning the following question:

My most gracious fellow Monks,

I'm trying to get a handle on Class::Multimethods but I can't seem to get it to do basic class accessor methods when if nothing is passed to the method it just returns the class field for the method, otherwise if a string is passed, it assigned that string to the field. For instance:

my $f = Flub->new("Cheese is Good."); print $f->flubble() . "\n"; $f->flubble("Cheese is Bad"); print $f->flubble() . "\n";
I know that this is easily possible doing basic Perl, but I'm hoping to get into fancier things after I figure out how this works.

My full code is below.

Thanks!

#!/usr/bin/perl -w package Flub; use strict; use Class::Multimethods; sub new { my ($class) = @_; bless { _flub => $_[1] || "", }, $class; } # new multimethod flubble => ('*') => sub { my ($self) = shift; return $self->{_flub}; }; multimethod flubble => ('$') => sub { my ($self) = shift; $self->{_flub} = shift; return $self->{_flub}; }; package main; use strict; my $f = Flub->new("Cheese is Good."); print "Trying to display \$f->{_flub}: " . $f->flubble() . "\n"; print "Trying to assign Cheese is Bad to \$f->{_flub}: " . $f->flubble("Cheese is Bad ") . "\n";

Replies are listed 'Best First'.
Re: Basic Accessor Methods using Class::Multimethods
by lachoy (Parson) on Feb 27, 2002 at 21:33 UTC

    I think if you just want accessor/mutator methods, you might be better off with a more focused module: Class::Accessor. It's extremely simple:

    package My::Class; use strict; use base qw( Class::Accessor ); My::Class->mk_accessors( qw( field1 field2 field3 ) );

    That's it! This creates the methods 'field1', 'field2', and 'field3' which act as accessors/mutators. You can also inherit a simple new() method and a number of other actions. IMO, the docs are well-written and easy to follow, and while there are a few dependencies the CPAN shell should TCB for you...

    Chris
    M-x auto-bs-mode

      Thanks for the replay. The problem is that I am trying to get Multimethods to do more complex stuff and I stumble over this simple problem.