http://www.perlmonks.org?node_id=1003939

reaper9187 has asked for the wisdom of the Perl Monks concerning the following question:

Hi
Jus a small question ... Is it possible to check if a particular key value pair entry exists in a hash , specifically in case of a key with multiple values ..????
  • Comment on Check if hash key value pair is defined

Replies are listed 'Best First'.
Re: Check if hash key value pair is defined
by davido (Cardinal) on Nov 15, 2012 at 07:10 UTC

    Keys in hashes are unique. The only way for a key to have multiple values is if the "value" is a reference to some container (an anonymous hash, anonymous array, or some object). Let's say your hash holds references to arrays. You might do this:

    my %hash = ( unwanted => [1], wanted => [2, 3, 4] ); my $target_key = 'wanted'; if( exists $hash{ $target_key } && ref $hash{ $target_key } eq 'ARRAY' && @{ $hash{ $target_key } } > 1 ) { print "The element associated with $target_key holds a reference t +o an array of @{$hash{$target_key}} values.\n"; }

    Dave

Re: Check if hash key value pair is defined
by tobyink (Canon) on Nov 15, 2012 at 07:13 UTC

    In a standard Perl hash, a key can only have one value. (Though that value could be a reference to an array.)

    # checking if this key-value pair exists my ($key, $value) = ("foo", "123"); # ... in this hash my %hash = ( foo => "123", bar => "456", ); if (exists $hash{$key} and $hash{$key} eq $value) { print "key-value pair exists\n"; }
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: Check if hash key value pair is defined
by Anonymous Monk on Nov 15, 2012 at 14:18 UTC
    A data structure as-described must consist of a hash whose values are arrayrefs (or hashrefs). Therefore, first check to see if the key exists(), then use e.g. grep() to look for the desired value.

    Be consistent: Arrange the program so that the hash always contains an arrayref, even if it contains only one entry. Perl's "auto-vivification" features make the necessary code for building the structure short-and-sweet.