• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 250
  • Last Modified:

using perl's match m/ in a if condition

using the m/ to match multiple options..
my $fallQ = func1();
# $fallQ could be any word, but i want a if condition which succeds only if the $fallQ is either ASM or ac or per. Alsothe match should be case insensitive..

i tried if ($fallQ =~ m/[AC|ASM|PER]/i) {
  #do important stuff;
}
But this did not work
0
pvinodp
Asked:
pvinodp
  • 3
3 Solutions
 
Carl BohmanCommented:
if ($fallQ =~ m/(AC|ASM|PER)/i) ...
0
 
Carl BohmanCommented:
The problem is that you are using square brackets [] which are used for character classes.  You need to use parentheses () to specify multiple options to match.

Note that the regex I gave will match any text that contains the given characters anywhere in the string.  To limit to only those exact strings, you need to anchor the match using carat ^ and dollar sign $:

if ($fallQ =~ m/^(AC|ASM|PER)$/i) ...
0
 
wilcoxonCommented:
Or, even better:

if ($fallQ =~ m/^(?:AC|ASM|PER)$/i) ...

Parens capture by default - adding ?: to the beginning of the parens will make it a non-capturing paren group.  Capture wastes resources if it is not necessary - however, unless this line will get executed many times, you'll never notice the difference (unless doing ms timings).
0
 
Carl BohmanCommented:
@wilcoxon: Agreed.  I normally do that by default, but was not certain whether the data would be used somewhere in the if block or not.  If it is needed in the block, capturing parentheses (...) will be necesary instead of non-capturing parentheses (?:...).
0
 
pvinodpAuthor Commented:
Thanks all
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now