|
NAMEHash::AsObject - treat hashes as objects, with arbitrary accessors/mutatorsSYNOPSIS$h = Hash::AsObject->new; $h->foo(123); print $h->foo; # prints 123 print $h->{'foo'}; # prints 123 $h->{'bar'}{'baz'} = 456; print $h->bar->baz; # prints 456 DESCRIPTIONA Hash::AsObject is a blessed hash that provides read-write access to its elements using accessors. (Actually, they're both accessors and mutators.)It's designed to act as much like a plain hash as possible; this means, for example, that you can use methods like "DESTROY" to get or set hash elements with that name. See below for more information. METHODSThe whole point of this module is to provide arbitrary methods. For the most part, these are defined at runtime by a specially written "AUTOLOAD" function.In order to behave properly in all cases, however, a number of special methods and functions must be supported. Some of these are defined while others are simply emulated in AUTOLOAD.
The methods "can()" and "isa()" are special, because they're defined in the "UNIVERSAL" class that all packages automatically inherit from. Unfortunately, this means that you can't use Hash::AsObject to access elements 'can' and 'isa'. CAVEATSNo distinction is made between non-existent elements and those that are present but undefined. Furthermore, there's no way to delete an element without resorting to "delete $h->{'foo'}".Storing a hash directly into an element of a Hash::AsObject instance has the effect of blessing that hash into Hash::AsObject. For example, the following code: my $h = Hash::AsObject->new; my $foo = { 'bar' => 1, 'baz' => 2 }; print ref($foo), "\n"; $h->foo($foo); print ref($foo), "\n"; Produces the following output: HASH Hash::AsObject I could fix this, but then code like the following would throw an exception, because "$h->foo($foo)" will return a plain hash reference, not an object: $h->foo($foo)->bar; Well, I can make "$h->foo($foo)->bar" work, but then code like this won't have the desired effect: my $foo = { 'bar' => 123 }; $h->foo($foo); $h->foo->bar(456); print $foo->{'bar'}; # prints 123 print $h->foo->bar; # prints 456 I suppose I could fix that, but that's an awful lot of work for little apparent benefit. Let me know if you have any thoughts on this. BUGSAutovivification is probably not emulated correctly.The blessing of hashes stored in a Hash::AsObject might be considered a bug. Or a feature; it depends on your point of view. TO DO
VERSION0.06AUTHORPaul Hoffman <nkuitse AT cpan DOT org>CREDITSAndy Wardley for Template::Stash, which was my inspiration. Writing template code like this:[% foo.bar.baz(qux) %] Made me yearn to write Perl code like this: foo->bar->baz($qux); COPYRIGHTCopyright 2003-2007 Paul M. Hoffman. All rights reserved.This program is free software; you can redistribute it and modify it under the same terms as Perl itself.
Visit the GSP FreeBSD Man Page Interface. |