Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: Tieing ans Blessing

by tobyink (Abbot)
on Oct 05, 2012 at 09:13 UTC ( #997414=note: print w/replies, xml ) Need Help??

in reply to Tieing and Blessing

Tied hashes are backed by objects. If you have a tied hash %foo then you can access the underlying object using tied(%foo). You can call methods on it like tied(%foo)->my_method(42).

If you have a tied hash, yes, it's also possible to bless a reference to that hash into a particular class. This may even be a different class to the one used to implement the tied behaviour.

And here's a quick example to show a hash tied to one class and blessed into another...

use v5.14; use Test::More; package MyClass 1.0 { sub new { my ($class, $hashref) = @_; bless $hashref => $class; } sub quux { return 'quuux'; } } use Hash::DefaultValue; # it's on CPAN tie my %hash, 'Hash::DefaultValue', 42; ok( $hash{hello} == 42, 'tie works properly', ); my $object = MyClass->new(\%hash); ok( $object->{world} == 42, 'tie works properly, even when blessed', ); ok( $object->isa('MyClass') && !$object->isa('Hash::DefaultValue'), 'blessed into the proper class' ); ok( tied(%$object)->isa('Hash::DefaultValue') && !tied(%$object)->isa( +'MyClass'), 'tied to the proper class' ); ok( $object->quux eq 'quuux', 'method calls on object work', ); done_testing();
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://997414]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (11)
As of 2018-06-22 17:44 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.