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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|