Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Answer: How do I make a constructor?

( #8185=categorized answer: print w/ replies, xml ) Need Help??

Q&A > object-oriented programming > How do I make a constructor? 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.

Comment on Answer: How do I make a constructor?
Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2014-12-18 23:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (69 votes), past polls