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

How can you check to see if $name and $pass in a hash exist and contain eachother? I know how to search a hash for a key to see if it exists but at the same time I need to see if $key eq $value as well. Something like this?

if ($var1 && $var2) { #if they are present if ((exists $hash{$var1}) && ($hash{$var1}=$var2) { # if it exists in +hash check to see if key has the right value print "Yup, they work" } else { print "Either it didn't exist or crudentials weren't matched"; }

Replies are listed 'Best First'.
Re: Existing in hash
by bart (Canon) on Apr 28, 2003 at 09:46 UTC
    Replace the "=" that TVSET pointed to, with "eq", and you're in business.
    if (exists $hash{$var1} && $hash{$var1} eq $var2) { print "Welcome\n"; }
Re: Existing in hash
by TVSET (Chaplain) on Apr 28, 2003 at 07:31 UTC
    The "=" sign in your if makes me wonder ;)
    Why don't you want to use something as simple as? :

    if ($hash{$var1} == $var2) { print "You are in\n"; } else { print "Bad, monkay, bad!\n"; }

    If you insist on more checks, you can do

    if (defined($var1)) { ... }

    thingy. Or you can even do

    if (defined($hash{$var1}) && length($hash{$var1}) > 0) { ... }

    staff. It's all up to you... :)

    Leonid Mamtchenkov

      I think you want eq instead of ==. This is not PHP, or Javascript, or whatever... :) In perl, == does numerical comparisons only.

        The == operator is best for comparing numbers, or for comparing for identical references (references to the same data object). The example here didn't give much to go on.

        If $var1 and $var2 are references, the $var1 eq $var2 would also work: it discovers that "HASH(0x804c88c)" eq "HASH(0x804c88c)", but takes the extra time to stringize both sides.

        --
        [ e d @ h a l l e y . c c ]