As for the source filter, I wonder if maybe you could use AUTOLOAD to generate the accessors when/if they are first used? The :Field attrib would store a reference to the hash and its name, and the generator would look it up to see if that name existed, without worrying about the scope of the underlying declared hash.

The problem is in getting the name of the hash.

If it's a global var then you can get at it via the GLOB Attribute::Handlers passes you. Which is easy.

Unfortunately all you get for a lexical variable is the string 'LEXICAL'. Since at the point the handler is called the variable isn't in the pad yet, you cannot get at it with PadWalker either.

As far as I can see the only way of getting the name for a lexically scoped hash is to use a source filter - but if anybody has a sneakier solution I'd love to hear it :-)

I did briefly consider :

my %foo : Field; # no accessor our %foo : Field; # accessor created automatically

but I couldn't really find a justification for overloading the meaning of our/my in this way.

I don't understand your DESTROY. You define $class on one line to be my blessed class, then define it again on the next line to be every key in the Values hash. Isn't this going to destroy all classes? That is, don't you want a single $values=$Values{$class}, rather than iterating over all $Values?

The line is redundent - hangover from an earlier version. Well spotted. I've removed it.

You don't want to just look at $Values{$class}, since you need to destroy inherited attributes too. So the DESTROY method deletes all instances of a particular object in all classes.

Why the overkill? Why not just check the @ISA hierarchy for the object? Because it might have been blessed into another class (e.g. when implementing a series of state classes).

Have a test script, just to reassure:

use Test::More tests => 3; use strict; use warnings; { package Foo; use base qw(Class::InsideOut); sub new { bless {}, shift }; my %foo :Field; sub foo { my $self = shift->self; @_ ? $foo{$self} = shift : $foo{$self}; }; sub Num_objects { scalar(keys(%foo)) }; package Bar; use base qw(Class::InsideOut); }; { my $o1 = Foo->new; $o1->foo(1); { my $o2 = Foo->new; $o2->foo(2); bless $o2, 'Bar'; is( Foo->Num_objects, 2, '2 objects' ); }; is( Foo->Num_objects, 1, '1 object' ); }; is( Foo->Num_objects, 0, '0 objects' );


1..3 + ok 1 - 2 objects + ok 2 - 1 object + ok 3 - 0 objects

You could make it more efficient (e.g. overload bless and keep track of what classes an object has been and only examine those hierarchies) - but I thought I'd keep it simple for now!

In reply to Re^2: Class::InsideOut - yet another riff on inside out objects. by adrianh
in thread Class::InsideOut - yet another riff on inside out objects. by adrianh

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":