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.";

In reply to Re: Re: Re: Tied HASH as boolean?! by sauoq
in thread Tied HASH as boolean?! by gmpassos

Title:
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, details, 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, summary, 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.