Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Multiple Strings In Perl

Tags:

perl

I have my code like this:

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

Is there anyways to optimize this. I want something like:

if ( $var eq ["str1" || "str2" || "str3"] ) {...}
like image 316
sundar Avatar asked Feb 06 '12 08:02

sundar


Video Answer


1 Answers

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}) { … }
like image 177
Marcelo Cantos Avatar answered Sep 27 '22 19:09

Marcelo Cantos