How to test a tied HASH as a boolean?

Take a look in this code, and you can see that the HASH is always FALSE as boolean.

my %hash ; tie(%hash , 'TiedHash') ; print "key: $hash{key}\n" ; if ( %hash ) { print "BOOL: 1\n" ;} else { print "BOOL: 0\n" ;} package TiedHash ; use overload ( 'bool' => sub{ print "OVER1!\n" ; } , ## print() return 1! '""' => sub{ print "OVER2!\n" ; } , '0+' => sub{ print "OVER3!\n" ; } , 'fallback' => 1 , ); sub TIEHASH { bless({}, __PACKAGE__ ) ;} sub FETCH { return( 'fetch_val' ) ;}
This was test on Perl-5.6.1-Win32 and Perl-5.8.0-Win32, with and without use overload and it always return FALSE!

Looking for a way to return TRUE for a tied HASH, I found that it looks for the value of the HASH not tied. Soo, the code that work is:

my %hash = (1) ; tie(%hash , 'TiedHash') ; if ( %hash ) { print "BOOL: 1\n" ;} else { print "BOOL: 0\n" ;} package TiedHash ; sub TIEHASH { bless({}, __PACKAGE__ ) ;}
In other words, the HASH need to have at least one KEY before TIE it, or the HASH will be FALSE as boolean!

I don't know if this is documented, but haven't found anything about it. I also think that it looks like a bug, since the value of the HASH as boolean (and string) need to be controled and changed (now is like a constant after tie it). The right way is to control this through overload or from some sub inside the TiedHash package (like FETCH).

Well, for me I just need to always have the HASH as TRUE, since I tie it only when I have keys. But in the future this can be changed in Perl, and my code wont work! I holp that I have helped some monks that had this problem too. ;-P

Graciliano M. P.
"The creativity is the expression of the liberty".


In reply to 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.