in reply to Smallish mock objects

Oog. I didn't know you could bless globs. Should you be able to? My first reaction is to call it a bug that it doesn't say "Can't bless non-reference value". Update: I was misremembering gensym as returning a glob; in fact it returns a globref and there's nothing wrong with blessing that.

gensym doesn't actually create namespaces; they spring into existence on demand. I would just have done something like:

my $obj = {}; my $class = "$obj"; bless $obj, $class; *{"${class}::foo"} = sub { "bar" }; print $obj->foo();

Replies are listed 'Best First'.
Re^2: Smallish mock objects
by ikegami (Patriarch) on Dec 25, 2006 at 03:01 UTC

    Oog. I didn't know you could bless globs

    ( Globs Glob refs ) are blessable and globs are tieable. Similarly, all IOs are blessed.

    >perl -e "open $fh, '-'; print *$fh{IO} IO::Handle=IO(0x22532c) >perl -e "print *STDOUT{IO} IO::Handle=IO(0x225cfc)

    That means all IOs can be used as objects.

    >perl -e "STDOUT->flush() Can't locate object method "flush" via package "IO::Handle" >perl -e "use IO::Handle; STDOUT->flush()
Re^2: Smallish mock objects
by diotalevi (Canon) on Dec 25, 2006 at 06:26 UTC

    You can have overlapping classes here. If $obj expires prior to this code executing again then you can have the same location-reused and you'd have the same class name for two different objects. Symbol does the work of maintaining a counter for me and applying it to a namespace. The following code is quite a bit lighter but it introduces the namespace Symbol::GEN1->GENinf.

    my $counter = 0; sub new { my $class = "Symbol::GEN$counter"; ++ $counter; return bless ..., $class; }

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊