Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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'

In reply to Re: Tieing ans Blessing by tobyink
in thread Tieing and Blessing by McA

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others lurking in the Monastery: (4)
    As of 2018-05-20 18:12 GMT
    Find Nodes?
      Voting Booth?