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
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
.
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";
}
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'; }
}
}
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.
精彩评论