dws has asked for the wisdom of the Perl Monks concerning the following question:

I was reading HTML::Template earlier today, and came across the following:
sub new { my $pkg = shift; my $self; { my %hash; $self = bless(\%hash, $pkg); }
This puzzled me. Why not just do
sub new { my $pkg = shift; my $self = bless {}, $pkg;
Is this a trick to make HTML::Template run under mod_perl? Superstition on the part of the author? Deep magic?Anyone?

Running into stuff like this throws me off balance; it feels like there's more going on than meets the eye.

Replies are listed 'Best First'.
(crazyinsomniac) Re: Odd constructor in HTML::Template
by crazyinsomniac (Prior) on Mar 29, 2002 at 07:24 UTC
      I believe it has something to do with the scope of the variables and the Authors attempt to force the $hash variable to be truly private. There is a great discussion of this in "Object Oriented Perl" by Damian Conway. If you do not have this book it is a must for any OOP Perl programmer and a great introduction to OOP with Perl.
        Except that it does nothing of the kind. There's no difference to creating a named lexical and letting it fall out of scope versus creating an anonymous value in the first place. So, perhaps this is vestigial code, left over from a larger cut-n-paste, or this is from someone who didn't quite "get it".

        In either case, I'd yellow flag this in a formal code review. Meaning I'd let it stand as workable, but if resources were available, bring it in line with more common idioms.

        -- Randal L. Schwartz, Perl hacker

      Definitely not a Perl 4 issue, since it had no references, and therefore no need/use for a bless() function. :-)

      (Not to mention a lack of modules.)

      Impossible Robot