1

I want to do something like

$val = "value1"
my %test = ("value1" => "yes", "value2" => "yes", "value3" => "yes");
print  $test{$val};

So if either $val is equal to either value1, value2 or value3 then display "yes" otherwise display "no"

Not sure if I'm doing it the correct/efficient way. I'm new to perl

4
  • 1
    Really, you should test if the key exists, then test if the value is defined, then test if it's equal to "yes". Yay perl. Commented Sep 13, 2011 at 14:33
  • @mkb: assuming that the hash is static and is composed only out of constants, checking whether a value is undefined is unnecessary. Commented Sep 13, 2011 at 14:36
  • @mkb You only need to check for exists and defined if a valid value of the key may be 0 or ''. Commented Sep 13, 2011 at 14:54
  • I'm just joking; I love perl, really. Commented Sep 13, 2011 at 15:20

4 Answers 4

3

You have to test whether a value with such a key exists in the hash:

print exists $tests{$val} ? $tests{$val} : "no";

In general, after checking for its existence, you have to check for its definedness via defined, but in your particular case this is not necessary since the %test hash seems to be constant and is composed only out of constants which do not include undef.

Sign up to request clarification or add additional context in comments.

1 Comment

You don't have to check if such a value exists. You only have to check if you want to use that particular value.
2
if (defined $test{$val}) {
    print "$test{$val}\n";  # or you might use: print "yes\n"; depending on what you're doing
}
else {
    print "no\n";
}

Comments

1

Is a hash the best possible data structure here when there are only two options? Here are three possible alternative subroutines that will equally satisfy the requirement:

sub test_ternary {
    $_[0] eq 'value1' ? 'yes' :
    $_[0] eq 'value2' ? 'yes' :
    $_[0] eq 'value3' ? 'yes' : 'no'  ;
}

sub test_regex { $_[0] =~ /value[123]/ ? 'yes' : 'no' }

use feature 'switch';
sub test_switch {
    given ( $_[0] ) {

        return 'yes' when /value[123]/;

        default { return 'no'; }
    }
}

2 Comments

It is tempting to benchmark and micro-optimize the three alternatives ;)
Don't forget smart match: print $value~~{"value1","value2","value3"]?"yes":"no"
0

Somewhat complicated answers here.

If the valid values in your hash can not be zero or empty string (or any other value which evaluates to "false" in perl), you can do:

say $test{$val} ? $test{$val} : "no";

This expression will be "false" if $test{$val} either does not exist, is undefined, is empty, or is zero.

1 Comment

say $test{$val} || 'no' if you are sure valid values in %test are always true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.