Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Tieing ans Blessing

by tobyink (Canon)
on Oct 05, 2012 at 09:13 UTC ( [id://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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://997414]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-03-19 11:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found