Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: A first attempt.. at OO perl

by TGI (Parson)
on Jul 02, 2008 at 17:43 UTC ( [id://695159]=note: print w/replies, xml ) Need Help??


in reply to A first attempt.. at OO perl

It looks like you've implemented everything as a class method.

Here's a jot of example code.

# ClassName->method( @args ); # class method # $object_ref->method( @args ); # instance method # calling your constructor. my $o = MyOptions->new( Usage => 'Do what I say, not what I do!', Options => [ { Name => 'Foo', Type => 'Bar', Etc => 'Blah' }, { Name => 'Bar', Type => 'Baz', Etc => 'Blah' }, ], ); $o->print_usage; MyOptions->debug(1); # having problems here. Enabling debug mode. my $chickens = $o->count_your_chickens($eggs); MyOptions->debug(0); my $parsed_ok = $o->parse_args( @ARGV ); package MyOptions; use const OPTIONS => 0, my $DEBUG; sub debug { my $old = $DEBUG; if ( @_ ) { my $old = $DEBUG; $DEBUG = shift; $Carp::Verbose = $DEBUG; } return $old; } sub new { my $class = shift; my %args = @_; my $self = []; bless $self, $class; $self->set_usage( $args{Usage} ); $self->add_options( @{ $args{Options} || [] } ); return $self; } sub set_usage { my $self = shift; check_args(@_,1); my $old_usage = $self->[USAGE]; $self->[USAGE] = shift; return $old_usage; } sub add_options { my $self = shift; foreach my $opt (@_) { my $opt_obj = $self->OptionFactory( $opt ); next unless $opt_obj; my $name = $opt_obj->get_name; $self->[OPTIONS]{ $name } = $opt_obj; } return keys %{$self->[OPTIONS]||{}}; } sub OptionFactory { my $self = shift; my $opt = shift; # make an option object from the specification passed in. # unless $opt is already an option object. Then return. # if opt is inavalid spec - return undef my $obj = UNIVERSAL::isa( 'MyOption', $opt ) ? $opt : MyOption->new(); return $obj; }

I can't recommend thedamian's Object Oriented Perl enough. Very good for the OOP newbie. It covers concepts of OO and interesting Perl techniques, mostly along the lines of classical Perl OO.

If you want to do really fancy OO stuff check out Moose. It's all the rage these days. I recommend learning to do the classical style first.


TGI says moo

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2024-04-19 17:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found