dragonchild has asked for the wisdom of the Perl Monks concerning the following question:

According to both tie and perltie, tie() returns back the result of calling new() in your class. So, from what I understand, tie @array, 'My::Class', @params; will return back the result of My::Class->new(@params);

So, a few questions:

  1. If I call tie() from within new(), why isn't that an infinite loop?
  2. If I don't provide a new(), why is tie() returning a blessed hashref? More importantly, from where?!

Update: Yet, again, I should have treated PM as a teddybear and hit preview first. According to tie (which I thought I'd read thoroughly):

Any additional arguments are passed to the new method of the class (meaning TIESCALAR , TIEHANDLE , TIEARRAY , or TIEHASH ).

There is no reference to new(). Please feel free to -- this node. :-|


My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

Replies are listed 'Best First'.
Re: The return value of tie()
by Limbic~Region (Chancellor) on Feb 17, 2006 at 20:31 UTC
    dragonchild,
    Well, to know for sure I would need to see the TIEARRAY sub from My::Class, but I think you are misreading tie. The new() function for a tied class is replaced by "TIESCALAR", "TIEHANDLE", "TIEARRAY", or "TIEHASH".

    As for why it is returning a blessed reference - that's what it supposed to do. That is so you can create a hybrid OO and tied object to do things like:

    my $obj = tie my @array, 'My::Class'; $obj->some_method;
    The uglier way to do that without storing the return value is to do:
    (tied @array)->some_method();
    It is important to note that you should undef $obj before trying to untie @array. Ultimately the underlying object needn't be the same type as the user sees. If you look under the covers of my Tie::Hash::Sorted, you will see that the hash is really an array under the covers.

    If you want to post more code of My::Class I would be happy to take a look.

    Cheers - L~R