Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Blessing tied hash

by davido (Archbishop)
on May 05, 2012 at 15:36 UTC ( #969051=note: print w/replies, xml ) Need Help??

in reply to Blessing tied hash

As has been mentioned, a hash itself cannot be blessed, but a hashref (including a tied one) can. However, I wanted to add that there is another abstraction already available when a hash gets tied.

Let's tie %hash:

tie my %hash, MyClass; # boring

tie has a return value...

my $tied_object = tie my %hash, MyClass; # fun! $object->frobcinate(42);

Now what you're proposing is that the reference to %hash also be blessed:

my $tied_object = tie my %hash, MyClass; my $instance = bless \%hash, MyOtherClass; $tied_object->frobcinate(42); $instance->bedazzle( with => 'evil' );

These are two different objects, tied to two very different classes. $tied_object could, for example, explicitly call FETCH(), and may call any other methods built into MyClass. On the other hand, $instance can call any methods from MyOtherClass. Neither one of them has any direct access to the other; they're two separate objects.

As authors (which I'm not) often say, "The implementation and application to real world problems is left as an exercise for the reader."

Now according to perltie, the object reference returned by tie doesn't even have to be a reference to an object of type MyClass (the tied class). Thus it's possible that $tied_object be blessed into some other class entirely. Update:...of the same type as the variable being tied. Thus, you might tie a hash, but return a reference to a blessed filehandle, or coderef or something like that. More evil. (and a little different from what I originally suggested)


Replies are listed 'Best First'.
Re^2: Blessing tied hash
by anazawa (Scribe) on May 05, 2012 at 16:16 UTC
    I agree $tied_object and $instance are two separate objects. Though the following:
    bless \%hash, MyOtherClass;
    makes \%hash blessed into MyOtherClass, I don't think $tied_object blessed into the same class at the same time. In fact,
    ref $tied_object
    returns 'MyClass'.
Re^2: Blessing tied hash
by anazawa (Scribe) on May 05, 2012 at 16:39 UTC
    I misunderstood. In your last paragraph, you maybe mean we can:
    bless $tied_object, 'Foo';
    but we shouldn't do so.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2018-02-22 23:28 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (300 votes). Check out past polls.