Decrypter
Decrypter

Reputation: 3000

map many strings to one string in perl

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

Upvotes: 1

Views: 212

Answers (4)

Zaid
Zaid

Reputation: 37136

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'; }
    }
}

Upvotes: 1

TLP
TLP

Reputation: 67900

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.

Upvotes: 0

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43498

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.

Upvotes: 3

Alex Reynolds
Alex Reynolds

Reputation: 96927

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";
}

Upvotes: 2

Related Questions