perl hashref查找函数始终返回默认值

时间:2016-04-02 21:29:36

标签: perl hash hashref

我有以下函数,当我在hashref中查找键和值时,应该返回true或false。我确定我错过了什么但是什么?

如果找到我们搜索的键值字符串,函数shoudl将返回true或false。

#!/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";
}

2 个答案:

答案 0 :(得分:1)

  1. $findkey =~ m/^$hashkey$/应为$hashkey =~ m/^$findkey$/
  2. 您返回0,在找到匹配的键/值对时在Perl中转换为false,在找不到对时返回1(true)。为什么?扭转这种逻辑。要返回false,请使用简单的return;,不带任何参数。

答案 1 :(得分:0)

您将哈希用作键/值对的数组,而不是使用内容寻址功能,这可以使这更快,更简洁。没有必要检查每个哈希的所有元素

#!/usr/bin/perl

use strict;
use warnings;

my $structure = {
    Key1 => { Key4 => "findme", Key5 => 9, Key6 => 10 },
    Key2 => { Key7 => "abc",    Key8 => 9 },
};

sub lookup_key_value {

    my ( $hash, $findkey, $findvalue ) = @_;

    my $val = $hash->{$findkey};

    if ( not ref $val ) {
        return 1 if defined $val and $val eq $findvalue;
    }

    for $val ( grep { ref eq 'HASH' } values %$hash ) {
        return 1 if lookup_key_value( $val, $findkey, $findvalue );
    }

    return;
}

print lookup_key_value( $structure, 'Key7', 'abcX' ) ? "FOUND !\n" : "MISSING !\n";

输出

MISSING !