But, I must take exception with one of the conclusions you're implying. The error in line 14 is caused by the fact that your new() method isn't verifying that it was actually passed anything.
I know thats why its happening, you know why its happening, but does Joe-Perl-Newbie know why? Maybe, maybe not. The error message given points back to the $foo->test line, which it not the actual source of the issue. IMO, its just adds to the insidiousness of this.
As for a way to solve this, code-wise, I am currently toying with using this:
sub new {
my ($class) = @_;
$class = ref($class) || $class;
(UNIVERSAL::isa($class, __PACKAGE__)
|| UNIVERSAL::isa(__PACKAGE__, $class))
|| die "Oh no you don't!!!!";
bless {}, $class;
}
It works (or rather doesn't work) in all the following conditions:
Foo::new();
Foo::new("SomeOtherModuleName") ;
Foo::new([]);
Foo::new({});
As well as works correctly when inherited. I am trying to think of other ways it might get used/abused to see how well it holds up. Any thoughts are appreciated.
But, we're just getting stupid. :-)
I know, isn't it fun ;-P
UPDATE:
I think this would actually be the most thorough approach, even though I think UNIVERSAL::isa probably handles $class being undef okay.
sub new {
my ($class) = @_;
$class = ref($class) || $class;
(defined $class &&
(UNIVERSAL::isa($class, __PACKAGE__)
|| UNIVERSAL::isa(__PACKAGE__, $class)))
|| die "Oh no you don't!!!!";
bless {}, $class;
}
-
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.