Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Answer: How do I make a constructor?

by jamesduncan (Novice)
on Apr 08, 2003 at 11:34 UTC ( #248886=categorized answer: print w/replies, xml ) Need Help??

Q&A > object-oriented programming > How do I make a constructor? - Answer contributed by jamesduncan

I tend to use:
sub new { my $class = shift; my $self = {}; if (bless( $self, $class)->init( @_ )) { return $self; } else { # throw some sort of error } } sub init { 1; }
That way all subclasses can initialize themselves in a standard way with something along the lines of:
sub init { my $self = shift; if ($self->SUPER::init( @_ )) { ## do some sort of initialization ## or return false return 1; } else { return 0; } }
and I'll know if something goes wrong...

Replies are listed 'Best First'.
Re: Answer: How do I make a constructor? (different responsibilities)
by Aristotle (Chancellor) on Apr 13, 2003 at 12:51 UTC
    I'd be inclined to write that as follows:
    sub new { return (bless {}, shift)->init(@_); } sub init { my $self = shift; $self->SUPER::init(@_); 1 # put stuff to initialize here or die "Failed to init $self: blah blah\n"; return $self; }

    Makeshifts last the longest.

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
[shmem]: you get a file named tags where all symbols and the places where they are used are listed
[Lady_Aleena]: geany may not support that.
[shmem]: I see that there is a plugin geany-plugin- codenav
[shmem]: maybe that supports ctags, check the documentation
[Lady_Aleena]: I'd have to talk to a geany person to see.
[Lady_Aleena]: Right now, I'm trying to decide whether I want to rewrite how variables are entered in the sub I'm working on.
[shmem]: wait, what? you want that person to read the documentation for you?
[Lady_Aleena]: I might have to go with options instead of a straight list.
[Discipulus]: if more than 3 go for named variables LA

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (12)
As of 2017-04-27 12:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (506 votes). Check out past polls.