I'd like to get people's thoughts on this proposed module, especially
its name (Class::* doesn't seem right; Hash::Methods wouldn't be bad). 
If I don't hear anything bad, I'll go ahead and upload it to CPAN.

I like how you can do things like this in the Template Toolkit:

    [% SET foo = bar.baz.qux %]

..without having to know if bar and bar.baz are hashrefs or objects (or
even coderefs).  So I whipped up a lightweight module (nothing but an
AUTOLOAD method) that lets you do something similar in Perl:

    use Hash::ObjectLike;
    %H = (
        foo => {
            bar => {
                baz => 123, ...
            }, ...
        }, ...
    );
    $foo = Hash::ObjectLike->new(\%H);
    print $foo->bar->baz;  # prints 123
    $foo->bar->baz(456);
    print $foo->bar->baz;  # prints 456

Any hash ref retrieved for a Hash::ObjectLike instance is automatically
blessed into Hash::ObjectLike (unless it's already blessed as something
else).

Class::Hash doesn't autobless, so you can't use a call chain like
$foo->bar->baz->qux unless each of the intermediates isa Class::Hash.

Class::Accessor, Class::Struct, and Class::MethodMaker are vaguely
similar.

Excerpts from the module's documentation...


NAME
       Hash::ObjectLike - hashes with accessors/mutators

SYNOPSIS
           $h = Hash::ObjectLike->new;
           $h->foo(123);
           print $h->foo;       # prints 123
           $h->bar->baz(456);
           print $h->bar->baz;  # prints 456

DESCRIPTION
       An instance of Hash::ObjectLike is a blessed hash that
       provides read-write access to its elements using methods.

PUBLIC METHODS

       new
              $h = Hash::ObjectLike->new;
              $h = Hash::ObjectLike->new($some_hash);

CAVEATS
       No distinction is made between non-existent elements and
       those are present but undefined.  Furthermore, there's no
       way to delete an element without resorting to C<< delete
       $h->{foo} >>.

       Storing a plain hash ref directly into an element of a
       Hash::ObjectLike instance has the effect of blessing that
       hash into Hash::ObjectLike.

       For example, the following code:

           my $h = Hash::ObjectLike->new;
           my $foo = { bar => 1, baz => 2 };
           print ref($foo), "\n";
           $h->foo($foo);
           print ref($foo), "\n";

       Produces the following output:

           HASH
           Hash::ObjectLike

Reply via email to