I'm amazed that
merlyn didn't pipe up in this thread. :-)
Your ref construction is the one he disliked at ref($proto) - just say no!. (Further explanation available at A Cat's eye view of OO.) Unless you really think that you will be using new as a clone() method, you can drop that one. Furthermore, while you are at it, the usual way that new will be called is with the package name (aka class) as the first argument. Calling it $obj is misleading at best. Furthermore if you have gone to the work of creating a hash, why dereference it and build another to take a reference to that? You had a perfectly good hash.
With those changes your code turns into:
package HeckIfIKnow;
sub new {
my ($class, %opts) = @_;
return bless(\%opts, $class);
}
Now for where you call it. The keyword is
package, not Package. You need a ;, not a :. You have to make it a method call, not a function call. And given that you don't have to tell data from metadata, there is no need to make all of your options have - in the name (and it is customary not to). With that in mind the rest of your code becomes:
package main;
my $foo = HeckIfIKnow->new(
opt1 => '3456',
opt2 => '1234',
);
Yes, you can reduce the boilerplate further than this with a variety of modules. But my advice is that until you are comfortable with the mechanics of how Perl does things, that you put off piling on shortcuts and complications.
-
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.