On 4/4/06, Lawrence Statton <[EMAIL PROTECTED]> wrote: > > Is there a nice clean perl way to test to see if only one key of a hash > > has data? > > > > %some_hash = ( key1 => 1, key2 => 2 ); should fail the test > > %some_hash = ( key2 => 2 ); should pass the test > > %some_hash = ( key1 => 1 ); should pass the test > > %some_hash = ( key1 => 1, key2 => 2, key3 => 3 ); should fail the test > > %some_hash = ( key2 => 2 ); should pass the test > > %some_hash = ( key1 => 1 ); should pass the test > > %some_hash = ( key2 => 2, key3 => 3 ); should pass the test > > %some_hash = ( key1 => 1, key3 => 3 ); should pass the test > > > > Basically I can many more keys in the hash but two of the keys have to > > be exclusive. > > > > You really could have said that a LOT better... It took several > re-readings, and finally "what's the difference between test-cases 1, > 7 and 8?" to understand what you meant. > > How 'bout > > Given a hash %hash with many keys ( qw / key1 key2 key3 keyn / ) > how do I test that only one of the values $hash{key1} or $hash{key2} are > defined? > > if ( exists $hash{key1} and exists $hash{key2} ) { > warn "fail"; > } else { > warn "succeed"; > }
You've said two differnt things here, though, and they may be important to the OP, although he hasn't been very clear. If you want to know whether a value is defined, you don't use exists, you use defined. Consider #!/usr/bin/perl use warnings; use strict; my %hash = ( 0 => 0, 1 => 1, 2 => 2, 3 => undef, 4 => '' ); foreach my $key (keys %hash) { print "key $key "; print "exists" if exists $hash{$key}; print ", is defined" if defined $hash{$key}; print ", is true" if $hash{$key}; print "\n"; } print "2 & 3 both exist\n" if exists $hash{2} && exists $hash{3}; print "2 & 3 aren't both defined\n" unless defined $hash{2} && defined $hash{3}; print "2 & 3 aren't both true\n" unless $hash{2} && $hash{3}; print "5 didn't even come to the party\n" unless exists $hash{5}; The first step is for OP to decide what question he really wants to ask about his data. HTH, -- jay -------------------------------------------------- This email and attachment(s): [ ] blogable; [ x ] ask first; [ ] private and confidential daggerquill [at] gmail [dot] com http://www.tuaw.com http://www.dpguru.com http://www.engatiki.org values of β will give rise to dom!