Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Answer: How do I make a constructor?

by chromatic (Archbishop)
on Apr 20, 2000 at 20:35 UTC ( #8185=categorized answer: print w/replies, xml ) Need Help??

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

Simply create a subroutine that initializes something, blesses a reference to it into the appropriate class, and returns the blessed reference. There is no enforced naming scheme (as there is in C++ or Java, for example), but many Perl hackers use new:
sub new { my $class = shift; # allow for inheritance $class = ref($class) || $class; # allow indirect or # direct calling my $self = {}; # create an anonymous # array to hold member data bless($self, $class); # allow for inheritance return $self; # return new object }
That's the canonical constructor. It takes the name of the class into which to bless the object (provided automatically), discerns the proper name (whether it is called through an instance of that class or indirect means), creates an anonymous hash for member data, uses the dual-argument form of bless to be sure that the object is created as a type of the desired (not just the current) class, and provides it to the caller in a nicely wrapped package.

You will probably want to be in your own package before you declare this constructor, though.

Log In?

What's my password?
Create A New User
[erix]: AngloZionist
[shmem]: and it is *not* pro-russian. It describes the western world.
[erix]: I'm not going to read it so I could be mistaken but it reeks of useful idiocy
[shmem]: AngloZionist is not an antisemitic term.
[shmem]: erix: be assured that we all are horribly mistaken, always. What would we write tests for, if not for that fact?
[shmem]: and then, audiatur et altera pars.
[erix]: and what's the "Vineyard"? Don't tell me it's doing supernatural stuff too.
[shmem]: go figure. Might help to open views to other ways of perceiving reality. No, no supernatural stuff.
[shmem]: the "Vineyard" is a biblic term, also. But that's not the point.

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2018-03-19 20:59 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (246 votes). Check out past polls.