in reply to max_strl - Get length of longest string in a hash

Rather than iterating through the hash each time you need to figure out the longest value, I'd tie the hash such that it kept track of the longest whenever the contents change. Then you could do:
$maxlength = length(tied(%hash)->longestvalue());
or something like that.

Replies are listed 'Best First'.
Re: Re: max_strl - Get length of longest string in a hash
by liz (Monsignor) on Aug 21, 2003 at 10:20 UTC
    Hmmm... and how would that be able to take care of:

    $hash{a} = '1234567'; $hash{b} = '12345678'; $hash{c} = '123456789'; delete $hash{c};
    in other words: when the longest is deleted, which one is then the longest? You would need to set a flag that would force a re-scan on delete of the longest.

    Implementation details, maybe, but also maybe a can of worms you don't want to get into... ;-)

    Liz

      Like this . Pretty trivial really, once you've figured out what all the possibilities are - and writing the tests first really helps. It copes with items being deleted and with items being changed, only rescanning when absolutely necessary.

      I shall now cross all my fingers and toes and hope there's no bugs :-)

        Looks good. But it seems that you're polluting the hash with keys KEY, VALUE, CURRENT_STATE and RESCAN_NEEDED. Although the chance that an actual application would use those keys is small, it is not 0.

        You might want to bless the object as a list ref with two hash refs: one with the actual hash info, and one with your state maintenance. That way they will never be able to interfere with each other. But this will slow down access to the hash even further though. YMMV.

        Liz