如何检查hasharray中是否存在密钥并具有特定值 - Perl

时间:2018-01-23 18:38:09

标签: arrays perl hash key

我有哈希数组:

my %hash = (
    'DISK'    => 1,
    'MEMORY'  => 1,
    'CPU'     => 0,
    'SSL'     => 1,
    'PROCESS' => 1,
);

功能:

sub fun
{
    my $self = shift;
    my @ret = ();
    my $index = 0;
    my ($alarm, $hash) = @_;
    my $key = "CPU";

    print "Key: $_ and Value: $hash->{$_}\n" foreach (keys %{$hash});

    foreach my $name (keys %{$self->{ServerParameters}})
    {
            my $par = uc $name;
            $par =~ s/\d$//g;

            if (!defined ${${$self->{ServerParameters}}{$name}}{$alarm})
            {
                    next;
            }
            if (${${$self->{ServerParameters}}{$name}}{$alarm} eq "1")
            {       
                    if (exists $hash{$par}){
                        if ($hash{$par} == 0){
                            print "VALUE 0\n";
                        }
                    }
                    my $param = ${$self->{ServerParameters}}{$name}->getValues();
                    $ret[$index++] = "Alarm parameter: $par : $param";
            }
    }
    return @ret;
}

我将哈希数组传递给上面的函数:

fun("Red", \%hash);

首先,我试图检查是否存在特定密钥,然后检查它的值是否为0.当尝试运行上面的代码时,我收到:

全局符号“%hash”需要显式包名称

如何使用例如grep进行类似的检查?感谢任何帮助。

1 个答案:

答案 0 :(得分:-1)

When you do this:

fun("Red", \%hash);

You're sending in a hash reference, not a hash. There's two ways to fix this.

One, the easiest, send in the hash. I would recommend using the second approach below, unless you've got a lot of code/many subroutines to update.

fun("Red", %hash);

...then change:

my ($alarm, $hash) = @_;

to:

my ($alarm, %hash) = @_;

That'll alleviate any other code changes.

Second, instead of changing the call and the assignment of the parameter(s) per the example above, you will have to change all uses to the hash within your code to a hash reference. For example:

if (exists $hash->{$par}){
    if ($hash->{$par} == 0){
        print "VALUE 0\n";
    }
}

There's no real right or wrong way, it really depends what you're doing with the code inside of the subroutine.

Sending in a hash makes a copy (ie. you now have two instances of the hash floating around, which may be problematic depending on the size of the hash. In this case, it's negligible to say the least). Changing the data in the hash within the sub does not change the outer-scoped hash.

Sending in a reference does not make a copy which reduces memory footprint, but any changes to the hash reference within the sub will change the original hash outside of the sub.