in reply to Tieing anonymous hashes

Essentially, what appears within the tie function must have a sigil. That means that tie expects an actual hash, not a hashref. The {...} anonymous hash constructor returns a hashref, which doesn't work. For example:

tie( %hash, 'Class' );

...is valid, but ...

tie( { anon => 'hash' }, 'Class' );

...is not valid. However, you can tie the nested portions of nested datastructures like this:

my $href = {}; tie( %{$href}, 'Class' );

...or even...

my( %hash ) = ( 'this' => {}, 'that' => {} ); tie( %{$hash{'this'}}, 'Class' );

Also note, definately it is not doing what you expect if you do this:

my( %hash ) = tie( %otherhash, 'Class' );

...because tie doesn't return the tied hash, it returns the tied object's instance reference. Since you're assigning the object's reference to %hash, you'll stringify the object ref and turn it into a hash key in %hash with undef as the value. So don't do that. In other words, this does work:

my $obj = tie( %hash, 'Class' ); $obj->DESTROY;

Dave

Replies are listed 'Best First'.
Re^2: Tieing anonymous hashes
by diotalevi (Canon) on Jun 28, 2005 at 22:26 UTC

    In other words, this does work:

    my $obj = tie( %hash, 'Class' ); $obj->DESTROY;

    It works except that you'd never, ever write code to call ->DESTROY because that's only ever called by perl when it is actually destroying something. ->DESTROY doesn't provoke a cleanup - its only something that happens during cleanup.

      You are correct, sir.
      I was demonstrating that the return value of tie is an object reference that could be treated as such. My choice of DESTROY in the example was to use a method I knew should exist regardless of the class to which the variable is tied, that is common in any old ordinary class, and that people familiar with OO would visually recognize as a method call. But you're absolutely right about letting Perl call DESTROY().


      Dave

        So use ->can() or ->isa().