Hash::AutoHash(3pm)
π Hash::AutoHash π
okay bestie, listen up β this is the manual page for Hash::AutoHash (that's the Hash::AutoHash(3pm) one, from the User Contributed Perl Documentation section, iykyk). It gives you object-oriented access to real AND tied hashes. Yes, both. She's versatile like that. β¨
π VERSION
Version 1.17
β¨ SYNOPSIS β¨
use Hash::AutoHash;
# real hash
my $autohash=new Hash::AutoHash name=>'Joe', hobbies=>['hiking','cooking'];
# access or change hash elements via methods
my $name=$autohash->name; # 'Joe'
my $hobbies=$autohash->hobbies; # ['hiking','cooking']
$autohash->hobbies(['go','chess']); # hobbies now ['go','chess']
# you can also use standard hash notation and functions
my($name,$hobbies)=@$autohash{qw(name hobbies)};
$autohash->{name}='Moe'; # name now 'Moe'
my @values=values %$autohash; # ('Moe',['go','chess'])
# tied hash.
use Hash::AutoHash qw(autohash_tie);
use Tie::Hash::MultiValue; # from CPAN. each hash element is ARRAY
my $autohash=autohash_tie Tie::Hash::MultiValue;
$autohash->name('Joe');
$autohash->hobbies('hiking','cooking');
my $name=$autohash->name; # ['Joe']
my $hobbies=$autohash->hobbies; # ['hiking','cooking']
# real hash via constructor function. analogous to autohash_tied
use Hash::AutoHash qw(autohash_hash);
my $autohash=autohash_hash name=>'Joe',hobbies=>['hiking','cooking'];
my $name=$autohash->name; # 'Joe'
my $hobbies=$autohash->hobbies; # ['hiking','cooking']
# autohash_set is easy way to set multiple elements at once
# it has two forms
autohash_set($autohash,name=>'Moe',hobbies=>['go','chess']);
autohash_set($autohash,['name','hobbies'],['Moe',['go','chess']]);
# alias $autohash to regular hash for more concise hash notation
use Hash::AutoHash qw(autohash_alias);
my %hash;
autohash_alias($autohash,%hash);
# access or change hash elements without using ->
$hash{name}='Joe'; # changes $autohash and %hash
my $name_via_hash=$hash{name}; # 'Joe'
my $name_via_autohash=$autohash->name; # 'Joe'
# get two elements in one statement
my($name,$hobbies)=@hash{qw(name hobbies)};
# nested structures work, too, of course
my $name=autohash_hash first=>'Joe',last=>'Doe';
my $person=autohash_hash name=>$name,hobbies=>['hiking','cooking'];
my $first=$person->name->first; # 'Joe'
π DESCRIPTION π
So. This is yet another module that lets you access or change the elements of a hash using methods with the same name as the element's key. She's walking in the footsteps of Hash::AsObject, Hash::Inflator, Data::OpenStruct::Deep, Object::AutoAccessor, and probably a whole bunch of others, fr fr. π
But here's the main character difference: this module supports tied hashes, not just regular hashes. Which means a modular division of labor β this class is generic and treats all hashes the same way, and any special semantics come from the tied hash itself. Chef's kiss. π
The class has a 'new' method but also supplies several functions for constructing new Hash::AutoHash objects.
The constructor functions shown in the SYNOPSIS are literally all you need for typical uses, bestie. autohash_hash creates a new 'real' (ie, not tied) Hash::AutoHash object; autohash_tie creates a new tied Hash::AutoHash object. Once the objects are constructed, the class treats them the same way. Equality, periodt. β¨
You can get the value of a hash element using hash notation, or by invoking a method with the same name as the key. For example, these two are equivalent:
my $name=$autohash->{name};
my $name=$autohash->name;
You can also change the value of an element using either notation:
$autohash->{name}='Jonathan';
$autohash->name('Jonathan');
And you can add new elements using either notation:
$autohash->{first_name}='Joe';
$autohash->last_name('Plumber');
π¨ CAUTIONS π¨
- When using method notation, keys must be syntactically legal method names and cannot include
'funny'characters. - INCOMPATIBLE CHANGE: As of version
1.14, it is no longer possible to use method notation for keys with the same names as methods inherited fromUNIVERSAL(the base class of everything). These are'can','isa','DOES', and'VERSION'. The reason is that as of Perl5.9.3, callingUNIVERSALmethods as functions is deprecated and developers are encouraged to use method form instead. Previous versions of AutoHash are incompatible with CPAN modules that adopt this style.
okay this next bit is important, don't scroll past it π β nested structures work straightforwardly. If a value is aHash::AutoHashobject, you can use a series of'->'operators to get to its elements.
my $name=autohash_hash first=>'Joe',last=>'Doe';
my $person=autohash_hash name=>$name,hobbies=>['hiking','cooking'];
my $first=$person->name->first; # $name is 'Joe'
The class provides a full plate of functions for performing hash operations on Hash::AutoHash objects. These are useful if you want to avoid hash notation all together. The following example uses these functions to removes hash elements whose values are undefined:
use Hash::AutoHash qw(autohash_keys autohash_delete);
my @keys=autohash_keys($autohash);
for my $key (@keys) {
autohash_delete($autohash,$key) unless defined $autohash->$key;
}
The autohash_set function is an easy way to set multiple elements at once. This is especially handy for setting the initial value of a tied Hash::AutoHash object, in cases where the tied hash cannot do this directly.
use Hash::AutoHash qw(autohash_set);
my $autohash=autohash_tie Tie::Hash::MultiValue;
autohash_set($autohash,name=>'Joe',hobbies=>'hiking',hobbies=>'cooking');
In the example above, 'hobbies' is set twice, because that's how Tie::Hash::MultiValue lets you set a multi-valued element. Setting the element to an ARRAY of values doesn't do it. sneaky, right?? π
You can also feed autohash_set separate ARRAYs of keys and values.
my $autohash=autohash_tie Tie::Hash::MultiValue;
autohash_set($autohash,['name','hobbies'],['Joe','hiking']);
You can alias the object to a regular hash for more concise hash notation.
use Hash::AutoHash qw(autohash_alias);
my $autohash=autohash_tie Tie::Hash::MultiValue;
autohash_alias($autohash,%hash);
$hash{name}='Joe'; # changes both $autohash and %hash
$autohash->hobbies('kayaking'); # changes both $autohash and %hash
my($name,$hobbies)=@hash{qw(name hobbies)};
By aliasing $autohash to %hash, you avoid the need to dereference the variable when using hash notation. Admittedly, this is a minor convenience, but the reduction in verbosity can be useful in some cases. little things, y'know? π¦
It is also possible to link a Hash::AutoHash object to an existing hash which may be real or tied β a process we call wrapping. The effect is similar to aliasing. The difference is that with aliasing, the object exists first whereas with wrapping, the hash exists first.
# wrap existing hash - can be real or tied.
use Hash::AutoHash qw(autohash_wrap);
my %hash=(name=>'Moe',hobbies=>['running','rowing']);
my $autohash=autohash_wrap %hash;
my($name,$hobbies)=@hash{qw(name hobbies)};
$hash{name}='Joe'; # changes both $autohash and %hash
$autohash->hobbies('kayaking'); # changes both $autohash and %hash
If the Hash::AutoHash object is tied, the autohash_tied function returns the object implementing the tied hash. If the Hash::AutoHash object is aliased to a hash, the function also works on the hash. autohash_tied is almost equivalent to Perl's built-in tied function; see "Accessing the tied object" for details.
use Hash::AutoHash qw(autohash_tied);
my $autohash=autohash_tie Tie::Hash::MultiValue;
my $tied=autohash_tied($autohash); # Tie::Hash::MultiValue object
autohash_alias($autohash,%hash);
my $tied=autohash_tied(%hash); # same object as above
If you're certain the Hash::AutoHash object is tied, you can invoke methods on the tied object as follows. CAUTION: this will generate an error if the object is not tied. π
my $result=autohash_tied($autohash)->some_method(@parameters);
A safer way is to supply the method name and parameters as additional arguments to the autohash_tied function. This will return undef if the object is not tied.
my $result=autohash_tied($autohash,'some_method',@parameters);
π§Ή Keeping the namespace clean π§Ή
Hash::AutoHash provides all of its capabilities through class methods (these are methods, such as 'new', that are invoked on the class rather than on individual objects) or through functions that must be imported into the caller's namespace. In most cases, a method invoked on an object is interpreted as a request to access or change an element of the underlying hash.
CAUTION: As of version1.14, it is not possible to use method notation for keys with the same names as methods inherited fromUNIVERSAL(the base class of everything). These are'can','isa','DOES', and'VERSION'. The reason is that as of Perl5.9.3, callingUNIVERSALmethods as functions is deprecated and developers are encouraged to use method form instead. Previous versions of AutoHash are incompatible with CPAN modules that adopt this style.
Special care is needed with methods used implicitly by Perl to implement common features ('import', 'AUTOLOAD', 'DESTROY').
'import' is usually invoked by Perl as a class method when processing 'use' statements to import functions into the caller's namespace. We preserve this behavior but when invoked on an object, we interpret the call as a request to access or change the element of the underlying hash whose kye is 'import'. (yes, "kye". we're keeping that typo, it's part of the lore now π)
'AUTOLOAD' and 'DESTROY' pose different problems, since they are logically object methods. Fortunately, Perl leaves enough clues to let us tell whether these methods were called by Perl or directly by the application. When called by Perl, they operate as Perl expects; when called by the application, they access the underlying hash. she's smart like that π§
The 'new' method warrants special mention. In normal use, 'new' is almost always invoked as a class method, eg,
new Hash::AutoHash(name=>'Joe')
This invokes the 'new' method on Hash::AutoHash which constructs a new object as expected. If, however, 'new' is invoked on an object, eg,
$autohash->new
the code accesses the hash element named 'new'. π
π Constructors π
Hash::AutoHash provides a number of constructor functions as well as a 'new' method which is simply a front-end for the constructor functions. To use the constructor functions, you must import them into the caller's namespace using the common Perl idiom of listing the desired functions in a 'use' statement.
use Hash::AutoHash qw(autohash_hash autohash_tie autohash_wrap autohash_wrapobj
autohash_wraptie autohash_new);
autohash_hash
- Title:
autohash_hash - Usage:
$autohash=autohash_hash name=>'Joe',hobbies=>['hiking','cooking'] - Function: makes you a real Hash::AutoHash object β like, an actual one, not tied β and if you want, you can hand it some starting values right away β¨
- Returns: a Hash::AutoHash object π«Ά
- Args: optional list of
key=>valuepairs. No pressure. You can pass zero. She'll still show up π
π autohash_tie
- Title:
autohash_tie - Usage:
$autohash=autohash_tie Tie::Hash::MultiValue - Function: makes you a Hash::AutoHash object that is tied π
- Returns: a Hash::AutoHash object, tied to whatever class you named
- Args: the class that implements the tied hash β quotes are optional β plus any extra params, which get passed straight through to the
TIEHASHconstructor
okay so here's the tea: the object that autohash_tie hands you is simultaneously a Hash::AutoHash object and a tied hash. two things, one girl. main character energy fr fr π
so if you want the object that's actually implementing the tied hash (aka the thing Perl's tie function gives back), you've got two ways to get her:
my $tied=tied %$autohash; # note '%' before '$'
my $tied=autohash_tied($autohash); # note no '%' before '$'
β οΈ bestie, look at the sigils.%$autohashhas the%.autohash_tied($autohash)does not. that's the whole difference and yes it will bite you if you're not paying attention π
and then there's autohash_set, which is lowkey the MVP when the tied hash just cannot set its own initial value directly. she steps in and handles it:
use Hash::AutoHash qw(autohash_set);
my $autohash=autohash_tie Tie::Hash::MultiValue;
autohash_set ($autohash,name=>'Joe',hobbies=>'hiking',hobbies=>'cooking');
see how 'hobbies' shows up twice? yeah that's not a typo, that's the whole point π that is literally how Tie::Hash::MultiValue lets you set a multi-valued element. if you try to set the element to an ARRAY of values instead? it doesn't work. it's giving nothing. don't do it π
you can also feed autohash_set separate ARRAYs β one of keys, one of values:
my $autohash=autohash_tie Tie::Hash::MultiValue;
autohash_set($autohash,['name','hobbies'],['Joe','hiking']);
π¦ Wrapping an existing hash or tied object
the constructor functions in this section let you build a Hash::AutoHash object that's linked to a hash or tied object that already exists. we call this wrapping π
and once that linkage is made? the object and the hash have identical contents, periodt. change one, the other one changes too. they're matching. they're a set. it's giving soulmates π
autohash_wrap
- Title:
autohash_wrap - Usage:
$autohash=autohash_wrap %hash,name=>'Joe',hobbies=>['hiking','cooking'] - Function: creates a Hash::AutoHash object linked to the hash. the object starts out with whatever value the hash currently has. any extra parameters you pass are
key=>valuepairs used to set further elements of the object (and, obviously, of the hash too) - Returns: a Hash::AutoHash object linked to the hash π
- Args: a hash, plus an optional list of
key=>valuepairs. the hash can be real or tied β either is fine. thekey=>valuepairs set further elements of the object (and the hash) - Notes: if the hash is tied, the constructed object gets tied to the object implementing the tied hash. if the hash is not tied, the constructed object gets tied to an object of type
Hash::AutoHash::dup, which is the thing that implements the linking π«Ά
autohash_wrapobj
- Title:
autohash_wrapobj - Usage:
$autohash=autohash_wrapobj $tied_object,name=>'Joe',hobbies=>'hiking' - Function: creates a Hash::AutoHash object linked to a tied hash β but you give it the object implementing the tie (in other words, the object returned by Perl's
tiefunction). the constructed object starts with whatever value the hash currently has, and any extra parameters arekey=>valuepairs that set further elements of the object (and hash) - Returns: a Hash::AutoHash object linked to the hash
- Args: an object implementing a tied hash, plus an optional list of
key=>valuepairs. thekey=>valuepairs set further elements of the object (and hash)
here's another look at autohash_wrapobj, and honestly this one's probably more typical π:
$autohash=autohash_wrapobj tie %hash,'Tie::Hash::MultiValue'
and you can set initial values on the constructed object by just tossing them in as parameters β just wrap them in parentheses so they stay separate from the parameters going to tie. every single parenthesis in the example below is necessary. all of them. do not remove one. i'm serious π
$autohash=autohash_wrapobj ((tie %hash,'Tie::Hash::MultiValue'),
name=>'Joe',hobbies=>'hiking',hobbies=>'cooking')
autohash_wraptie
- Title:
autohash_wraptie - Usage:
$autohash=autohash_wraptie %hash,Tie::Hash::MultiValue - Function: creates a Hash::AutoHash object linked to a tied hash and does the tying, all in one step. two birds, one slay π¦
- Returns: a Hash::AutoHash object linked to the hash. side effect alert π¨ β the hash gets tied to the given class
- Args: a hash, plus the class implementing the tied hash (quotes are optional). any additional parameters are passed to the
TIEHASHconstructor - Notes: this is equivalent to
$autohash=autohash_wrapobj tie %hash,'Tie::Hash::MultiValue'
β¨ new
new and autohash_new are front-ends to all those other constructor functions. to accommodate the diversity of the other functions, the parameter syntax makes some assumptions and is not completely general. she's flexible, not omniscient, okay? π
- Title:
new - Usage:
$autohash=new Hash::AutoHash
name=>'Joe',hobbies=>['hiking','cooking']
-- OR --
$autohash=new Hash::AutoHash ['Tie::Hash::MultiValue'],
name=>'Joe',hobbies=>'hiking',hobbies=>'cooking'
-- OR --
$autohash=new Hash::AutoHash \%hash,
name=>'Joe',hobbies=>'hiking',hobbies=>'cooking'
-- OR --
$autohash=new Hash::AutoHash $tied_object,
name=>'Joe',hobbies=>'hiking',hobbies=>'cooking'
-- OR --
$autohash=new Hash::AutoHash [\%hash,'Tie::Hash::MultiValue'],
name=>'Joe',hobbies=>'hiking',hobbies=>'cooking'
- Function: creates a Hash::AutoHash object and optionally sets elements.
- Form 1, like
autohash_hash, creates a real (ie, not tied) object - Form 2, like
autohash_tie, creates a tied object - Form 3, like
autohash_wrap, creates an object linked to a hash - Form 4, like
autohash_wrapobj, creates an object linked to a tied hash given the object implementing the tie - Form 5, like
autohash_wraptie, creates an object linked to a tied hash and does the tie in one step
- Form 1, like
- Returns: a Hash::AutoHash object π«Ά
- Args: the first argument determines the form. the remaining arguments are an optional list of
key=>valuepairs used to set elements of the object.- Form 1. first argument is a scalar (eg, a string)
- Form 2. first argument is an ARRAY whose elements are the class implementing the tied hash (quotes are required) followed by additional parameters for the
TIEHASHconstructor - Form 3. first argument is a HASH that doesn't look like a tied object. see form 4
- Form 4. first argument is a HASH that looks like a tied object; this is any blessed HASH that provides a
TIEHASHmethod - Form 5. first argument is an ARRAY whose elements are a HASH and the class implementing the tied hash (quotes are required) followed by additional parameters for the
TIEHASHconstructor
πΈ autohash_new
like new, autohash_new is a front-end to the other constructor functions. we provide it purely for stylistic consistency π
to accommodate the diversity of the other functions, the parameter syntax makes some assumptions and is not completely general.
- Title:
autohash_new - Usage:
$autohash=autohash_new name=>'Joe',hobbies=>['hiking','cooking']
-- OR --
$autohash=autohash_new ['Tie::Hash::MultiValue'],
name=>'Joe',hobbies=>'hiking',hobbies=>'cooking'
-- OR --
$autohash=autohash_new \%hash,
name=>'Joe',hobbies=>'hiking',hobbies=>'cooking'
-- OR --
$autohash=autohash_new $tied_object,
name=>'Joe',hobbies=>'hiking',hobbies=>'cooking'
-- OR --
$autohash=autohash_new [\%hash,'Tie::Hash::MultiValue'],
name=>'Joe',hobbies=>'hiking',hobbies=>'cooking'
- Function: same as
new - Returns: a Hash::AutoHash object
- Args: same as
new
π§ Aliasing: autohash_alias
you can alias a Hash::AutoHash object to a regular hash, which means you skip the whole dereferencing-every-two-seconds thing when you want to use hash notation. it's the same vibe as wrapping an existing hash with autohash_wrap... except the order's flipped π
- with aliasing, the Hash::AutoHash object exists first, and you're linking a hash to it
- with wrapping, the hash exists first
once the linkage is made, the contents of the object and the hash are identical, and any change to one shows up in the other. no cap π
and as a little convenience, the autoahash_alias functions can link in either direction, depending on whether the object you handed over actually exists or not:
- Title:
autohash_alias - Usage:
autohash_alias($autohash,%hash) - Function: if
$autohashis defined and is a Hash::AutoHash object, link$autohashto%hash. if$autohashis not defined, create a new Hash::AutoHash object that wraps%hash - Args: a Hash::AutoHash object or
undef, plus a hash - Returns: a Hash::AutoHash object
π Getting and setting hash elements
one way to get and set hash elements is to just... treat the object like a HASH and use standard hash notation. iconic. effortless. π₯
my $autohash=autohash_hash name=>'Joe',hobbies=>['hiking','cooking'];
my $name=$autohash->{name};
my($name,$hobbies)=@$autohash{qw(name hobbies)};
$autohash->{name}='Moe';
@$autohash{qw(name hobbies)}=('Joe',['running','rowing']);
a second approach is to invoke a method named after the key. yes really. π
$autohash->name;
$autohash->name('Moe'); # sets name to 'Moe'
$autohash->hobbies(['blading','rowing']); # sets hobbies to ['blading','rowing']
and new hash elements? you can add those with either notation, so go off:
$autohash->{first_name}='Joe';
$autohash->last_name('Plumber');
also β if your object wraps or aliases a hash, you can just operate on the hash instead of on the Hash::AutoHash object. that can be way more concise, because you're not dereferencing the object over and over like it's your job π
use Hash::AutoHash qw(autohash_alias);
autohash_alias($autohash,%hash);
my $name=$hash{name}; # instead of $autohash->{name}
my @keys=keys %hash; # instead of keys %$autohash
okay so bestie, your class also serves two functions for wholesale manipulation of arguments. To use them, you gotta import them into the caller's namespace using the classic Perl idiom of listing the desired functions in a use statement. π
use Hash::AutoHash qw(autohash_get autohash_set);
β¨ autohash_get β¨
- Title:
autohash_get - Usage:
($name,$hobbies)=autohash_get($autohash,qw(name hobbies)) - Function: grab values for multiple keys. π
- Args: a
Hash::AutoHashobject and a list of keys - Returns: a list of argument values
β¨ autohash_set β¨
- Title:
autohash_set - Usage:
autohash_set($autohash,name=>'Joe Plumber',first_name=>'Joe')
-- OR --
autohash_set($autohash,['name','first_name'],['Joe Plumber','Joe'])
- Function: set multiple arguments in an existing object.
- Args: Form 1.
Hash::AutoHashobject and list ofkey=>valuepairs. Form 2.Hash::AutoHashobject,ARRAYof keys,ARRAYof values. - Returns:
Hash::AutoHashobject
β¨ Functions for hash-like operations β¨
These functions give you hash-like operations on Hash::AutoHash objects. They're useful if you wanna avoid hash notation all together. To use these functions, you must import them into the caller's namespace using the common Perl idiom of listing the desired functions in a use statement. π«Ά
use Hash::AutoHash
qw(autohash_clear autohash_delete autohash_each autohash_exists
autohash_keys autohash_values
autohash_count autohash_empty autohash_notempty);
πΈ autohash_clear πΈ
- Title:
autohash_clear - Usage:
autohash_clear($autohash) - Function: delete entire contents of
$autohash - Args:
Hash::AutoHashobject - Returns: nothing
πΈ autohash_delete πΈ
- Title:
autohash_delete - Usage:
autohash_delete($autohash,@keys) - Function: delete keys and their values from
$autohash. - Args:
Hash::AutoHashobject, list of keys - Returns: nothing
πΈ autohash_exists πΈ
- Title:
autohash_exists - Usage:
if (autohash_exists($autohash,$key)) { ... } - Function: test whether key is present in
$autohash. - Args:
Hash::AutoHashobject, key - Returns: boolean
πΈ autohash_each πΈ
- Title:
autohash_each - Usage:
while (my($key,$value)=autohash_each($autohash)) { ... }
-- OR --
while (my $key=autohash_each($autohash)) { ... }
- Function: iterate over all
key=>valuepairs or all keys present in$autohash - Args:
Hash::AutoHashobject - Returns:
- list context: next
key=>valuepair in$autohashor empty list at end - scalar context: next key in
$autohashorundefat end
- list context: next
πΈ autohash_keys πΈ
- Title:
autohash_keys - Usage:
@keys=autohash_keys($autohash) - Function: get all keys that are present in
$autohash - Args:
Hash::AutoHashobject - Returns: list of keys
πΈ autohash_values πΈ
- Title:
autohash_values - Usage:
@values=autohash_values($autohash) - Function: get the values of all keys that are present in
$autohash - Args:
Hash::AutoHashobject - Returns: list of values
πΈ autohash_count πΈ
- Title:
autohash_count - Usage:
$count=autohash_count($autohash) - Function: get how many keys are present in
$autohash - Args:
Hash::AutoHashobject - Returns: number
πΈ autohash_empty πΈ
- Title:
autohash_empty - Usage:
if (autohash_empty($autohash)) { ... } - Function: test whether
$autohashis empty - Args:
Hash::AutoHashobject - Returns: boolean
πΈ autohash_notempty πΈ
- Title:
autohash_notempty - Usage:
if (autohash_notempty($autohash)) { ... } - Function: test whether
$autohashis not empty. Complement ofautohash_empty - Args:
Hash::AutoHashobject - Returns: boolean
π¦ Accessing the tied object: autohash_tied π¦
okay so if a Hash::AutoHash object is tied, sometimes your app needs to get at the object that implements the underlying tied hash. That object is what we call the 'tied object'. Why? Because, for example, the tied object might have options that change how the tied hash works. π
In many cases, you can access the tied object using Perl's built-in tied function.
my $autohash=autohash_tie Tie::Hash::MultiValue;
my $tied=tied %$autohash; # note leading '%'
But bestie, Perl's built-in tied function does NOT do the right thing when the Hash::AutoHash object wraps or is aliased to a regular (not tied) hash. In those cases, the code uses an internal tied hash to connect the Hash::AutoHash object and the hash. (The internal tied hash is currently named Hash::AutoHash::alias, but that's subject to change, so don't get too attached.) π
The autohash_tied function is the safer glow-up way to get the tied object. In most cases, it's equivalent to Perl's built-in tied function, but it reaches through the internal Hash::AutoHash::alias object when one is there. π«Ά
If the Hash::AutoHash object is aliased to a hash, the function also works on the hash.
use Hash::AutoHash qw(autohash_tied);
my $autohash=autohash_tie Tie::Hash::MultiValue;
my $tied=autohash_tied($autohash); # Tie::Hash::MultiValue object
autohash_alias($autohash,%hash);
my $tied=autohash_tied(%hash); # same object as above
If you're certain the Hash::AutoHash object is tied, you can invoke methods on the result of autohash_tied. This will generate an error if the object is not tied. A safer way is to supply the method name and parameters as additional arguments to the autohash_tied function. This will return undef if the object is not tied. π₯
# two ways to invoke method on tied object
# 1st generates error if $autohash not tied
# 2nd returns undef if $autohash not tied
my $result=autohash_tied($autohash)->some_method(@parameters);
my $result=autohash_tied($autohash,'some_method',@parameters);
β¨ autohash_tied β¨
use Hash::AutoHash qw(autohash_tied);
- Title:
autohash_tied - Usage:
$tied=autohash_tied($autohash)
-- OR --
$tied=autohash_tied(%hash)
-- OR --
$result=autohash_tied($autohash,'some_method',@parameters)
-- OR --
$result=autohash_tied(%hash,'some_method',@parameters)
- Function: The first two forms return the object implementing the tied hash that underlies a
Hash::AutoHashobject if it is tied, orundefif it isn't tied. The latter two forms invoke a method on the tied object if theHash::AutoHashobject is tied, orundefif it isn't tied. In forms 1 and 3, the first argument is theHash::AutoHashobject. In forms 2 and 4, the first argument is a hash to which aHash::AutoHashobject has been aliased. - Returns: In forms 1 and 2, object implementing tied hash or
undef. In forms 3 and 4, result of invoking method (which can be anything or nothing), orundef. - Args:
- Form 1.
Hash::AutoHashobject - Form 2. hash to which
Hash::AutoHashobject is aliased - Form 3.
Hash::AutoHashobject, method name, optional list of parameters for method - Form 4. hash to which
Hash::AutoHashobject is aliased, method name, optional list of parameters for method
- Form 1.
𧬠Subclassing π§¬
okay so subclassing Hash::AutoHash has some special considerations, because it's trying to keep the namespace clean and it uses functions heavily instead of methods. π
A common use-case is a subclass that gives an object interface to a specific tied hash class. In that case, the subclass would probably have a new method that constructs objects tied to that class, and would probably want to hide the other constructor functions. The subclass might also want to provide the other functions from Hash::AutoHash (why not?) but might want to rename them to match the subclass's name. π
Here's an example subclass, TypicalChild, showing this use-case. TypicalChild gives you a new method that creates objects tied to Tie::Hash::MultiValue. The new method can also set the object's initial value (the TIEHASH method of Tie::Hash::MultiValue does not support that directly). The subclass provides the other functions from Hash::AutoHash but renames each from autohash_XXX to typicalchild_XXX. β¨
package TypicalChild;
use Hash::AutoHash;
our @ISA=qw(Hash::AutoHash);
our @NORMAL_EXPORT_OK=();
our %RENAME_EXPORT_OK=();
our @RENAME_EXPORT_OK=sub {s/^autohash/typicalchild/; $_};
our @EXPORT_OK=TypicalChild::helper->EXPORT_OK;
our @SUBCLASS_EXPORT_OK=TypicalChild::helper->SUBCLASS_EXPORT_OK;
#############################################################
# helper package to avoid polluting TypicalChild namespace
#############################################################
package TypicalChild::helper;
use Hash::AutoHash qw(autohash_tie autohash_set);
use Tie::Hash::MultiValue;
BEGIN {
our @ISA=qw(Hash::AutoHash::helper);
}
sub _new {
my($helper_class,$class,@args)=@_;
my $self=autohash_tie Tie::Hash::MultiValue;
autohash_set($self,@args);
bless $self,$class;
}
1;
The subclass is made of two packages: TypicalChild and TypicalChild::helper. The helper package is where all the real code lives, so it doesn't pollute TypicalChild's namespace. TypicalChild must be a subclass of Hash::AutoHash (so Hash::AutoHash must be in its @ISA array); TypicalChild::helper must be a subclass of Hash::AutoHash::helper (so Hash::AutoHash::helper must be in its @ISA array). π¦
The new method of Hash::AutoHash dispatches to the _new method in the helper class after making sure the method was invoked on a class. That's why the code has a _new method in TypicalChild::helper instead of a new method in TypicalChild. π
The BEGIN block is needed to make sure @ISA is set at compile-time before @EXPORT_OK is calculated.
The code in TypicalChild that deals with the various EXPORT_OK arrays handles renaming functions from Hash::AutoHash (or, more generally, any ancestor class), exporting additional functions defined by the subclass, and sets the stage for subclasses of the subclass to do the same thing. π
β¨ @NORMAL_EXPORT_OK β¨
- Variable:
@NORMAL_EXPORT_OK - Usage:
@NORMAL_EXPORT_OK=qw(autohash_set typicalchild_function) - Function: Functions that will be exported 'normally', in other words with no change of name. The functions can be defined here (in the helper class, not the main class!!) or in any ancestor class
okay bestie, we are still deep in the variable vault and these ones are the literal blueprint for how your subclass exports its functions π no cap, if you're building a subclass, this is your moment.
Variable: %NORMAL_EXPORT_OK
Usage:
%NORMAL_EXPORT_OK=(learn=>'autohash_set',forget=>'autohash_delete')
Function: These are the functions that will be exported with a different name. The left-hand side of each pair is the new name; the right-hand side is the name of a function defined here (in the helper class, not the main class!!) or in any ancestor class. periodt.
Variable: @RENAME_EXPORT_OK
Usage:
@RENAME_EXPORT_OK=sub {s/^autohash/typicalchild/; $_}
-- OR --
@RENAME_EXPORT_OK=(sub {s/^autohash/typicalchild/; $_},
qw(autohash_exists autohash_get))
Function: Functions that will be exported with a different name. This is the easy way to rename a whole bunch of functions at once. The first element of the list is a subroutine that will be applied to each other element of the list to generate the new names. The functions in the list can be defined here (in the helper class, not the main class!!) or in any ancestor class.
If the list of functions is empty, the subroutine is applied to everything in its parent classes' @SUBCLASS_EXPORT_OK array.
The form of the subroutine is exactly as for Perl's grep and map functions. iykyk.
Variable: @EXPORT_OK
Usage:
@EXPORT_OK=TypicalChild::helper->EXPORT_OK
-- OR --
@EXPORT_OK=qw(learn forget)
Function: Complete list of functions that the subclass is willing to export. The EXPORT_OK method computes this from the other variables. You can also set it explicitly. lowkey flexible.
Variable: @SUBCLASS_EXPORT_OK
Usage:
@SUBCLASS_EXPORT_OK=TypicalChild::helper->SUBCLASS_EXPORT_OK
-- OR --
@SUBCLASS_EXPORT_OK=qw(learn forget)
Function: Functions that subclasses of this class might want to export. This provides the default list of functions for @RENAME_EXPORT_OK in these subclasses. The SUBCLASS_EXPORT_OK method simply sets this to @EXPORT_OK, which is tantamount to assuming that subclasses may want to export everything this class exports. You can also set it explicitly. main character energy fr fr.
π SEE ALSO π
perltieandTie::Hashpresent background on tied hashes. vibe check: tied hashes 101.Hash::AsObject,Hash::Inflator,Data::OpenStruct::Deep, andObject::AutoAccessorare similar classes and may be better choices if you don't need or want to use tied hashes. The source code ofHash::AsObjectalerted us to the danger of methods inherited fromUNIVERSAL. β οΈ watch out for UNIVERSAL methods!Hash::AutoHash::Args,Hash::AutoHash::MultiValued,Hash::AutoHash::AVPairsSingle,Hash::AutoHash::AVPairsMulti,Hash::AutoHash::Recordare subclasses each of which provides an object interface to a specific tied hash class. so many flavors!Tie::Hash::MultiValueis a nice tied hash class used as an example throughout this POD. ate.- Many interesting tied hash classes are available on CPAN and can be found by searching for
'Tie::Hash'. go explore bestie!
βοΈ AUTHOR βοΈ
Nat Goodman, "<natg at shore.net>". iconic.
π BUGS AND CAVEATS π
Please report any bugs or feature requests to "bug-hash-autohash at rt.cpan.org", or through the web interface at <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Hash-AutoHash>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. teamwork makes the dream work.
π Known Bugs and Caveats π
- Overridden UNIVERSAL methods no longer supported
INCOMPATIBLE CHANGE: As of version 1.14, it is no longer possible to use method notation for keys with the same names as methods inherited from UNIVERSAL (the base class of everything). These are 'can', 'isa', 'DOES', and 'VERSION'. The reason is that as of Perl 5.9.3, calling UNIVERSAL methods as functions is deprecated and developers are encouraged to use method form instead. Previous versions of AutoHash are incompatible with CPAN modules that adopt this style. so don't do that.
- Tied hashes and serialization
Many serialization modules do not handle tied variables properly, and will not give correct results when applied to Hash::AutoHash objects that use tied hashes. In this context, "serialization" refers to the process of converting Perl data structures into strings that can be saved in files or elsewhere and later restored.
Storable handles tied hashes correctly and can be used to serialize all kinds of Hash::AutoHash objects.
Data::Dumper, YAML, and Data::Dump::Streamer do not handle tied hashes correctly and cannot be used to serialize Hash::AutoHash objects that use tied hashes. This includes objects created by the autohash_tie, autohash_wrap, and autohash_wrapobj functions (or by equivalent calls to 'new' or autohash_new). It also includes objects that have been aliased. The only Hash::AutoHash objects that can be serialized by these packages are real ones (ie, objects created by autohash_hash or equivalent calls to 'new' or autohash_new) that have not been aliased.
If you want to print Hash::AutoHash objects for debugging or testing purposes, Data::Dump works fine. However there is no way to recreate the objects from the printed form. ngl, that's a bummer.
- Tied hashes and prototypes considered harmful (by some)
This class uses tied hashes and subroutine prototypes, Perl features that Damian Conway urges programmers to avoid. Obviously, we disagree with Damian on this point, but we acknowledge the weight of his argument. respectful disagreement, periodt.
π SUPPORT π
You can find documentation for this module with the perldoc command.
perldoc Hash::AutoHash
You can also look for information at:
- RT: CPAN's request tracker
<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Hash-AutoHash>
- AnnoCPAN: Annotated CPAN documentation
<http://annocpan.org/dist/Hash-AutoHash>
- CPAN Ratings
<http://cpanratings.perl.org/d/Hash-AutoHash>
- Search CPAN
<http://search.cpan.org/dist/Hash-AutoHash/>
go get that info, bestie.
π COPYRIGHT & LICENSE π
Copyright (c) 2008, 2009 Institute for Systems Biology (ISB). All Rights Reserved.
This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.
See http://dev.perl.org/licenses/ for more information. slay, legally.
This iconic page was brought to you by Hash::AutoHash(3pm), perl v5.42.0, dated 2025-07-25. Stay slaying, bestie πβ¨π¦
π¦ where this page comes from
- fedora 43: perl-Hash-AutoHash 1.17-23.fc43 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms