Name
Util::H2O - Hash to Object: turns hashrefs into objects with accessors for keys
Synopsis
use Util::H2O;
my $hash = h2o { foo => "bar", x => "y" }, qw/ more keys /;
print $hash->foo, "\n"; # accessor
$hash->x("z"); # change value
$hash->more("quz"); # additional keys
my $struct = { hello => { perl => "world!" } };
h2o -recurse, $struct; # objectify nested hashrefs as well
print $struct->hello->perl, "\n";
my $obj = h2o -meth, { # code references become methods
what => "beans",
cool => sub {
my $self = shift;
print $self->what, "\n";
} };
$obj->cool; # prints "beans"
Description
This module allows you to turn hashrefs into objects, so that instead of $hash->{key}
you can write $hash->key
, plus you get protection from typos. In addition, options are provided that allow you to whip up really simple classes.
This module exports a single function by default.
h2o @opts, $hashref, @additional_keys
@opts
-recurse
-
Nested hashes are objectified as well. Note that none of the other options will be applied to the nested hashes, including
@additional_keys
. -meth
-
Any code references present in the hash will become methods.
-class => classname
-
Specify the class name into which to bless the object (as opposed to the default: a generated, unique package name in
Util::H2O::
).Warnings: If that package already exists, this may step on its toes! As opposed to the default behavior, the packages created with this option won't be cleaned up, so if you generate many of them, Perl's symbol table will fill up and use memory! Therefore, this option is really only meant for quick prototyping and testing.
$hashref
You must supply a plain (unblessed) hash reference here. Be aware that this function does modify the original hashref(s) by blessing it.
Note: The hash may not contain a key named DESTROY
, unless you've specified the -class
option.
@additional_keys
Methods will be set up for these keys even if they do not exist in the hash.
Returns
The (now blessed) $hashref
.
See Also
Inspired in part by lock_keys
from Hash::Util.
Many, many other modules exist to simplify object creation in Perl. This one is mine ;-P
For real OO work, I like Moo and Type::Tiny.
Author, Copyright, and License
Copyright (c) 2020 Hauke Daempfling (haukex@zero-g.net).
This library is free software; you can redistribute it and/or modify it under the same terms as Perl 5 itself.
For more information see the Perl Artistic License, which should have been distributed with your copy of Perl. Try the command perldoc perlartistic
or see http://perldoc.perl.org/perlartistic.html.