in reply to Object Oriented Programming in Perl.

Well, one piece of advice for OO in Perl which I myself picked up from this site (in dws's comments here), is that it's a tidy piece of good practice to separate your blessing from actually initialising your object variables. This requires 2 methods, which you might as well call sub new and sub initialise.

So for your constructor, you'd have:

package Food; sub new { my $class = shift; my $self = bless {}, $class; $self->initialize; $self; } sub initialize { my $self = shift; $self->{_beverage} = "Pepsi"; $self->{_entree} = "soup"; $self->{_dessert} = "ice cream"; }
I think it's conventional to put an underscore before your object variable names too, eg _beverage.

This may look like a bit of a waste of space, but its neatness might become a bit more obvious when you are actually passing initialisation info to the constructor (as opposed to everything starting off as Pepsi, soup, ice cream). Then you'd change the line in new to $self->initialize(@_);, and then have

sub initialize { my $self = shift; $self->{_beverage} = shift; $self->{_entree} = shift; $self->{_dessert} = shift; }
Call it with something like
my $meal = new Food("tea", "sushi", "creme egg");
HTH
Dennis

Replies are listed 'Best First'.
Re: Re: Object Oriented Programming in Perl.
by frankus (Priest) on Aug 05, 2002 at 09:42 UTC
    I think it's conventional to put an underscore before your object variable names too, eg _beverage.

    Erm, that's only for private properties, the rest are not prefixed with an underbar.
    From perltoot:

    Occasionally you'll see method names beginning or ending with an underscore or two. This marking is a convention indicating that the methods are private to that class alone and sometimes to its closest acquaintances, its immediate subclasses. But this distinction is not enforced by Perl itself. It's up to the programmer to behave.

    I feel your statement is misleading. New developers could use underbar incorrectly in their own code, and using other folks modules.

    --

    Brother Frankus.

    ¤