Why not adopt me?
NAME
Tie::InsideOut - Tie hashes to variables in caller's namespace
SYNOPSIS
use Tie::InsideOut;
our %GoodKey;
tie %hash, 'Tie::InsideOut';
...
$hash{GoodKey} = 1; # This will set a value in %GoodKey
$hash{BadKey} = 1; # This will cause an error if %BadKey does not exist
DESCRIPTION
This package ties hash so that the keys are the names of variables in the caller's namespace. If the variable does not exist, then attempts to access it will die.
An alternative namespace can be specified, if needed:
tie %hash, 'Tie::InsideOut', 'Other::Class';
This gives a convenient way to restrict valid hash keys, as well as provide a transparent implementation of inside-out objects, as with Class::Tie::InsideOut.
This package also tracks which keys were set, and attempts to delete keys when an object is destroyed so as to conserve resources. (Whether the overhead in tracking used keys outweighs the savings is yet to be determined.)
Note that your keys must be specified as our
variables so that they are accessible from outside of the class, and not as my
variables.
Serialization
Hashes can be serialized and deserialized using the Storable module's hooks:
use Tie::Hash 0.05; # version which added support
tie %hash, 'Tie::InsideOut';
...
my $frozen = freeze( \%hash );
my $thawed = thaw( $frozen );
my %copy = %{ $thawed };
or one can use the dclone
method
my $clone = dclone(\%hash);
my %copy = %{ $clone };
Deserializing into a different namespace than a tied hash was created in will cause errors.
Serialization using packages which do not use these hooks will not work.
KNOWN ISSUES
This version does little checking of the key names, beyond that there is a global hash variable with that name. It might be a hash intended as a field, or it might be one intended for something else. (You could hide them by specifying them as my
variables, though.)
There are no checks against using the name of a tied Tie::InsideOut or Class::Tie::InsideOut global hash variable as a key for itself, which has unpredicable (and possibly dangerous) results.
Keys are only accessible from the namespace that the hash was tied. If you pass the hash to a method in another object or a subroutine in another module, then it will not be able to access the keys. This is an intentional limitation for use with Class::Tie::InsideOut.
Because of this, naive serialization and cloning using packages like Data::Dumper will not work. See the "Serialization" section.
SEE ALSO
If you are looking for a method of restricting hash keys, try Hash::Utils.
AUTHOR
Robert Rothenberg <rrwo at cpan.org>
Suggestions and Bug Reporting
Feedback is always welcome. Please use the CPAN Request Tracker at http://rt.cpan.org to submit bug reports.
LICENSE
Copyright (c) 2006 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.