Comparing Multiple Strings In Perl

后端 未结 5 1631
广开言路
广开言路 2021-01-17 23:15

I have my code like this:

if ( $var eq \"str1\" || $var eq \"str2\" || $var eq \"str3\" )
{
...
}

Is there anyways to optimize this. I want

5条回答
  •  北海茫月
    2021-01-18 00:07

    Depending on the contents of the strings, a regex is quite convenient:

    if ($var =~ /^(str1|str2|str3)$/) { … }
    

    Failing that, you can grep over a list:

    if (grep { $var eq $_ } qw{str1 str2 str3}) { … }
    

提交回复
热议问题