pattern matching in perl


Is there an elegant way to pattern match a couple of patterns without having several or ( pattern1 || pattern2 || pattern3) in your code , specially when the $1,$2 matched patterns could differ based on which pattern actually matched.

I am trying to avoid having too many if -else - or else statements.

if (string=~pattern1)

else if(string=~pattern2)

else if(string=~pattern3)


Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

The best way to combine them would be to use named matches (added in perl 5.10 iirc).
# silly example but illustrates usage
if ($string =~ m{(?<name1>...)|(?<name2>...)}) {
    $name12 = defined($+{name1}) ? $+{name1} : $+{name2};

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Actually, depending on what you want to do, you may be looking for Switch ( or given (  Switch was part of the core until 5.10 or 5.12 (it can still be installed from CPAN).  given was added in 5.10 (I think).
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.