Perl has a new tied method for that since version 5.8.3: "SCALAR". You couldn't do it before that was added. It now also has heuristics to try to give a good scalar value even if you don't have a SCALAR method. On older perls you can try to make a replacement based on if FIRSTKEY returns something or not (but that implies changing the code that uses the hash in scalar context).

update Older perls returned whatever scalar context would return on the underlying hash that got tied. So if you make sure the hash is not empty before tying, the "if" will always be true, and as explained in a node below, the "while" in your code should then work correctly. So if that kind of use of the hash in scalar context is the only kind happening in your program, that should be a good enough workaround.


In reply to Re: Is it possible to control scalar(%h) when %h is a tied hash? by thospel
in thread Is it possible to control scalar(%h) when %h is a tied hash? by fizbin

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.