in reply to How best to tell when my hash is "full" (all values defined)?

Perhaps overkill for this application, but useful where the gathering of a predetermined set of fields is spread over a more complex gathering process.

  1. Predefine the hask keys, setting the values to undef.
  2. Use Internals::SetReadOnly to ensure that no other spurious keys can be autovivified accidentally.
  3. Use (Updated)keys( %hash ) == grep defined, values( %hash ) to ensure that you got them all.

    Or more simply, 0 == grep !defined, values %hash;

use Internals qw[ SetReadOnly ]; my %hash; undef @hash{ qw[ the quick brown fox ] }; SetReadOnly( \%hash ); ... while( <$fh> ) { if( ... some capturing regex ... ) { $hash{ $1 } = $2; } elsif( ... regex ... ) { $hash{ $1 } = $2; } else { $hash{ fox } == FOX_DEFAULT; } last if keys %hash == grep defined, values( %hash ); ## Updated, s +ee below. }

In the event that one of your regex accidentally matches the wrong key/value pairing, setting (say) $1 = 'bill', then you'll get a fatal error:

Attempt to access disallowed key 'bill' in a restricted hash at yoursc +ript.pl line nn, <$fh> line mm

Telling you not only which line of code the error occured, but also which line of the data file (and the value) that was involved.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^2: How best to tell when my hash is "full" (all values defined)?
by Hofmator (Curate) on Dec 18, 2006 at 15:31 UTC
    I'm not sure how your last-condition keys( %hash ) == values( %hash ) works ... isn't this always true for all hashes (the number of keys is equal to the number of values)?

    -- Hofmator

    Code written by Hofmator and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

      Yes, of course it should++. I was concentrating on the idea of avoiding accidental autovivification.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

      Yes. It should be

      keys( %hash ) == grep defined, values( %hash )

      (which can be simplified).