http://qs321.pair.com?node_id=375189

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

Today I was thinking about a not-so-recent post from Abigail-II where he created a tied scalar, tied to package main. I remembered thinking, "Oh, that's nifty." It hadn't really occurred to me (though the ability to do so does make perfect sense) that package main can be used as a class of which objects can be created.

But aside from this sort of quick-and-dirty tieing of a variable to an ad-hoc class in package main, is there any other reasonable use of the fact that main can, itself, be a class?

Consider the following contrived and dumb code:

package main; use strict; use warnings; sub new { my $class = shift; my $self = { Class => $class }; bless $self, $class; } sub myprint { my $self = shift; print "This is a method of class $self->{Class}.\n"; } my $obj = main->new(); $obj->myprint(); __OUTPUT__ This is a method of class main.

Ok, now I've created a more traditional object (more traditional than a tied variable), and have created it as class of main. And it has its own blessed hash for portable and compartmentalized namespace. But of what use is this?

My first thought when searching for a use of such a construct is that with this construct it becomes trivial to write script setup 'stuff' into the constructor sub, and cleanup stuff into the deconstructor sub. Why do it this way? ...not sure, but I had a brief and vague notion that in scripts that remain resident such as mod_perl it might somehow be useful for ensuring that each run has clean workspace.

But that's what lexical scoping does automatically anyway, and as for constructors and deconstructors, even without OO there exist BEGIN{ ... } and END{ ... } blocks.

Another thought I had is in the direction of the new() constructor spawning threads, but I don't know enough about threads to know if this is a useful way of handling them.

Of course another use of using main as a class might be for operator overloading, like tie, on a quick-and-dirty basis. But this is similar to the tie usage in a way, and feels unrewarding. Surely there is (or definitively is not) a good reason to create an object based on class main. Can anyone give a good usage of such a construct? Or is it just a feature that doesn't really have a good use?


Dave