perlperl-hash

Callback for hash property access in perl


Is there any native way in Perl to know what key of a hash was accessed?
Something like magic methods that exist in some languages or like a proxy object?


Solution

  • Yes, there is. It's called "tying" a variable.

    tie is a combination of instantiating a proxy object (from a specified class) and binding it to a variable.

    See perldoc perltie for details.

    The short version is:

    tie %hash, 'Some::Class';
    

    And then accessing %hash will trigger method calls in Some::Class (provided it implements a TIEHASH constructor and the rest of the interface).