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

Does anyone know how I would loop over the contents of a hash to figure out if one of it's contents matches a variable? I've got the way to do it on the top of my head, but can't remember. Which is really annoying. Any help?
Thanks,
Spidy

Replies are listed 'Best First'.
Re: Iterating over hash contents?
by Zaxo (Archbishop) on Aug 26, 2004 at 03:13 UTC

    my $matches = grep { $variable eq $_ } values %hash; That has $matches assigned to the number of hash values which match. String equality is tested; use '==' if you want a numeric match.

    After Compline,
    Zaxo

Re: Iterating over hash contents?
by ysth (Canon) on Aug 26, 2004 at 05:48 UTC
    Zaxo's answer is good if you don't need to know which key had a value that matched. In general, you loop over a hash in one of these ways:
    for my $value (values %hash) { # do something with $value } for my $key (keys %hash) { # do something with $key and $hash{$key} } # same as above, but sorted by value (or whatever) for my $key (sort { $hash{$a} cmp $hash{$b} } keys %hash) { } # with a while loop, you can bail out early without having # loaded all the keys on the stack up front; may be # more efficient for a large hash, or one tied to a dbm file. while (my $key = each %hash) { # note that there's an implicit defined() on the above assignment, # so the while loop continues to until each() returns undef # even if there are "0" or "" keys # do something with $key and $hash{$key} } # same as above, but go ahead and let list-context each # give both the key and the value while (my ($key, $value) = each %hash) { # above is a list assignment in scalar context, which evaluates to # the number of elements on the right of the assignment. # as long as each returns more data, the assignment will evaluate t +o 2 (true) # When the end is reached, each returns an empty list so the assign +ment # evaluates to 0. # do something with $key and $value }
Re: Iterating over hash contents?
by gaal (Parson) on Aug 26, 2004 at 05:22 UTC
    If you also want the keys to those elements whose values match your data, try this:
    my @keys_for_matching_values = grep { $hash{$_} eq $variable } keys %hash;
Re: Iterating over hash contents?
by Spidy (Chaplain) on Aug 30, 2004 at 22:31 UTC
    Does anyone know how I can check a DBM for matches to two variables? I'm connecting to it with a hash, using this:
    dbmopen(%HASH,dbm_db,0644);
    I want to check to see if $var1 equals the key, and then if $var2 equals the value. Does anyone know of a good way to do this?

    Thanks,
    Spidy