in reply to Re: Re: Tied HASH as boolean?!
in thread Tied HASH as boolean?!

I agree that there should be a way to do it but I don't think using overload would be the right way. Either one of the TIE* methods should be used or one should be added to give a hook allowing the programmer to set the value of a hash in scalar context.

Purely as a possible workaround, if you implement FIRSTKEY, NEXTKEY, and STORE, you can get a more useful truth value by forcing list context on the hash.

use Tie::Hash; tie my %h, 'Tie::StdHash'; # Check with an empty %h first... print "TRUE 1\n" if ( %h ); # Nope not true. print "TRUE 2\n" if ( ()=%h ); # Not true either. # Now a non-empty %h ... $h{foo} = "bar"; print "TRUE 3\n" if ( %h ); # Nope not true. print "TRUE 4\n" if ( ()=%h ); # Yes!
Of course, this comes with all sorts of huge caveats. Depending on the size of the hash it might not be realistic at all to do this for performance reasons. Your specific tie implementation might even make it an impossibility. (For instance, your list of keys needs to be finite; if it isn't the program will hang until it dies trying to allocate memory.) So, it's not an ideal solution, but just the same, it might work in many cases.

It really is too bad that you can't use syntax as simple as if ( %h ) { ... }.

-sauoq
"My two cents aren't worth a dime.";