Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Check if hash key value pair is defined

by reaper9187 (Scribe)
on Nov 15, 2012 at 07:03 UTC ( #1003939=perlquestion: print w/ replies, xml ) Need Help??
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
Re: Check if hash key value pair is defined
by davido (Archbishop) 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 (Abbot) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1003939]
Approved by tobyink
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2014-08-29 20:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (288 votes), past polls