While working on How's your Perl?, I was trying to find a way to create a blessed object without using bless. I stumbled across a couple:
open my $foo, ">&=STDOUT"; $foo = *$foo{IO}; print ref $foo
creates a IO handle with class IO::Handle (but doesn't actually load that module, which would violate the rules). (For backward compatibility, the class is actually FileHandle if you have used FileHandle and IO::Handle otherwise.)

Then I recalled a less intrusive way to do it:

select(select(my $foo)); $foo = *$foo{IO}; print ref $foo
There is actually a perl core module that uses this; I put the code there because I wanted to have a test in the core for this way of creating an IO handle without open, etc.

Unfortunately, this creates a second-class object. It doesn't honor overload in IO::Handle or FileHandle:

{ package FileHandle; use overload q[""]=>sub {"string me!"} } select(select(my $foo)); $foo = *$foo{IO}; print "$foo";
gives FileHandle=IO(0xa05c058) instead of the desired "string me!".

Then a little browsing through the perl source brought this builtin way to do it:

{ package PerlIO::Layer; use overload q[""]=>sub {"string me!"} } $foo = PerlIO::Layer->find("raw"); print "$foo"; # Update: this only works for 5.8.x (actually only tested on 5.8.2) # and not even then if you've built a perl without layers support.
Again, this doesn't actually load any module or use bless, but this time the overloading works. (Obviously overload itself is a module, but it is a pure perl module and you can duplicate how it works; getting that to work under use strict may be troublesome, but I think it is possible.)

My current attempts at answers are on my scratch pad. I've so far avoided looking at other's answers while I haven't given up hope on the remaining problems, so please no spoilers here (though comments on my answers so far would be nice).

Update: removed useless BEGIN's, double print

Replies are listed 'Best First'.
•Re: blessless blessing
by merlyn (Sage) on Dec 30, 2003 at 13:54 UTC
      The rules say no modules, no tie, no bless. It looks like you can create a AnyDBM_File::TIEHASH sub and avoid any module or literal tie, so this is a way to do a tieless tie; however, in the end, the TIEHASH sub has to do a bless.
Re: blessless blessing
by belg4mit (Prior) on Dec 30, 2003 at 15:32 UTC
    Umm, this is largely because you're running perl 5.8 Only the 2nd example works in pre 5.8 perl.

    --
    I'm not belgian but I play one on TV.

Re: blessless blessing
by Aristotle (Chancellor) on Dec 31, 2003 at 17:27 UTC
    print ref qr/foo/;

    Makeshifts last the longest.

      I thought I had tried that and that it didn't honor overload in Regexp, but it seems I was wrong. Thanks!