perlhashhashref

perl hashref lookup function always returning default value


I have the following function which SHOULD return true or false when I look up a key and value in a hashref. I am sure I am missing something but what ?

The function shoudl return true or false if the key value strings that we search for are found.

#!/usr/bin/perl
use warnings;
use strict;
my $structure = {
    Key1 => {
           Key4 => "findme",
           Key5 => 9,
           Key6 => 10,
         },
    Key2 => {
           Key7 => "abc",
           Key8 => 9,
             },
 };

sub lookup_key_value
{
    # Arguments are a hash ref and a list of keys to find
    my($hash,$findkey, $findvalue) = @_;

        # Loop over the keys in the hash
        foreach my $hashkey ( keys %{$hash})
        {

            # Get the value for the current key
            my $value = $hash->{$hashkey};

            # See if the value is a hash reference
            if (ref($value) eq 'HASH')
            {
                    # If it is call this function for that hash
                    &lookup_key_value($value,$findkey,$findvalue);
            }

            if ( ($findkey =~ m/^$hashkey$/) && ( $value =~ m/^$findvalue$/) )
            {
                print "$findkey = $hashkey, $value = $findvalue\n";
                return (0);
            }
        }
        return (1);
}

if ( &lookup_key_value($structure,"Key7","abcX") )
{
    print "FOUND !\n";
} else {
    print "MISSING !\n";
}

Solution

    1. This $findkey =~ m/^$hashkey$/ should be $hashkey =~ m/^$findkey$/
    2. You are returning 0, which translates to false in Perl, when matching key/value pair is found and returning 1 (true) when pair is not found. Why? Reverse this logic. To return false, use simple return;, without any arguments.