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 exports a single function by default.
h2o @opts, $hashref, @additional_keys
Turns hashrefs into objects, so that instead of $hash->{key}
you can write $hash->key
, plus you get protection from typos. Be aware that this does modify the original hashref.
Nested hashes can be objectified as well if you supply the -recurse
option as the first argument; additional keys apply to the toplevel hash only.
If you supply the -meth
option, then any code references present in the hash will become methods. Even when used together with -recurse
, only code references in the toplevel hash are methodified.
Note: The hash may not contain a key named DESTROY
.
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.