Number 1 is just weird
Actually, it does have some utility - and I've worked some places where it's the required style. Compare:
use strict;
use warnings;
use CGI;
# oops typo, but I don't get an error until runtime
sub foo { CGO->new };
# oops another typo, but this time I get a compile time error
sub bar { CGO::->new };
Handy for catching typos and missing use statements. | [reply] [d/l] |
Number 1 is just weird and number 2 doesn't compile.
Huh? 2 compiles perfectly well for me!
Also, in addition to the use that adrianh cited, 1 would be useful in the rare case in which one wants to use a class that has the same name as a subroutine defined in the client package. In such a case, as the OP has already noted, the parser gets confused with 3.
| [reply] [d/l] [select] |
wow, 2 questions:
1)Why does the Doggy.pm need the "#1;"?
2)And how did you get your post to collapse like that?
P.S. Perlmonks rule! thanks for the help guys.
| [reply] |
1)Why does the Doggy.pm need the "#1;"?
A module needs to end with a true value, 1; is the standard convention for that. You could also use "this is false";. It just has to be true. :)
2)And how did you get your post to collapse like that?
Enclose the poste in <readmore title="foo">text</readmore> tags
| [reply] [d/l] [select] |
1)Why does the Doggy.pm need the "#1;"?
Just to clarify holli's point, the value of the last statement in the module file to be evaluated must be true. That's why, in Doggie.pm the "1;" line is not the last line of the file; the subsequent lines consist entirely of subroutine definitions, which are not evaluated.
| [reply] |
Also in Doggy.pm I tried inserting the code:
print "$objref1->{'tail'}\n";
And I couldn't get it to print short. What am I doing wrong?
Sorry for all of the noob questions.
| [reply] |
As I defined it, the Doggie class has practically no API, other than the rather useless new method, which ignores its arguments and, despite its name, doesn't even return an object, new or otherwise! So the main thing you did wrong was trying to use a useless class :-) . (I wrote it that way just to illustrate that the code as written compiles and runs without errors or warnings.)
But even if new had returned an object, then most OO programmers will tell you that it is wrong software-engineering-wise to attempt to access $objref1->{'tail'}, because doing so "violates encapsulation", i.e. abuses a knowledge of how an object is implemented (in this case, presumably, as a hashref). In contrast to my Doggie, a well-designed class will provide accessors for those bits of instance data that are accessible to client code. I.e., you would invoke a method such as $objref1->tail.
BTW, just for the record, the variable name $objref1 (which I realize follows the example of PP3, p. 248) is somewhat redundant, because all Perl objects are references.
| [reply] |