in reply to Is it possible to control scalar(%h) when %h is a tied hash?

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.

  • Comment on Re: Is it possible to control scalar(%h) when %h is a tied hash?

Replies are listed 'Best First'.
Re^2: Is it possible to control scalar(%h) when %h is a tied hash?
by fizbin (Chaplain) on Oct 20, 2004 at 03:22 UTC
    Unfortunately, since I'm calling code in an external module, I can't really change it. Or rather, I can, but subclassing and doing a cut-and-paste of the whole large function is what I was trying to avoid doing by passing in a tied hash.
    -- @/=map{[/./g]}qw/.h_nJ Xapou cets krht ele_ r_ra/; map{y/X_/\n /;print}map{pop@$_}@/for@/
      You missed what he is saying. If you are using a version greater than 5.8.3, you can add a method, SCALAR, that gets called in exactly the circumstance you were asking about. No changing the module at all. (I haven't tested it, blah blah, just going off what the parent said, etc).
        Oh, no, I got that, but am stuck on an ActivePerl build of 5.6.1. I should have made it explicit when replying to someone mentioning SCALAR. (which, I'll admit, I didn't know about)
        -- @/=map{[/./g]}qw/.h_nJ Xapou cets krht ele_ r_ra/; map{y/X_/\n /;print}map{pop@$_}@/for@/
Re^2: Is it possible to control scalar(%h) when %h is a tied hash?
by fizbin (Chaplain) on Oct 20, 2004 at 17:13 UTC
    Ah! The update explains a way around it, and that's what I'll use to fix it, thanks.
    -- @/=map{[/./g]}qw/.h_nJ Xapou cets krht ele_ r_ra/; map{y/X_/\n /;print}map{pop@$_}@/for@/