pdubois
pdubois

Reputation: 7800

Checking whether a string does not present in hash

I want to perform a check with the following condition. If the member of %ans is not contained in %test, print that value of %ans. But why this didn't print it?

use Data::Dumper;
my %ans = ("foo" => 1);
my %test = ("bar" => 1);



foreach my $ansrule ( keys %{$ans}  ) {
    if ( !exists $test{$ansrule} ) {
        print "ANS: $ansrule\n";
    }
}

https://eval.in/51453

Upvotes: 1

Views: 104

Answers (2)

raina77ow
raina77ow

Reputation: 106483

Because keys %{$ans} is not the same as keys %ans, and you should've used the latter: $ans and %ans are different variables.

The %{$ans} attempts to dereference a hash ref stored in $ans variable - which is, apparently, not defined. Have you added use strict; to your code, you'd have seen the warning...

Global symbol "$ans" requires explicit package name

Upvotes: 2

mpapec
mpapec

Reputation: 50677

You want

foreach my $ansrule ( keys %ans  )

instead of

foreach my $ansrule ( keys %$ans  )

use strict; use warnings; would be helpful in detection of such flaws.

Upvotes: 2

Related Questions