in reply to Re^3: howto make a very long IF statment shorter
in thread howto make a very long IF statment shorter

Yes,
if ( $var_a =~ /^abcde$/ && $var_b =~ /^abcde$/ && ....
is not equivalent to
if (q{abcde} =~ /^(?=$var_a$)(?=$var_b$)(?=$var_c$)/)
but it is equivalent to
if (q{abcde} =~ /^(?=\Q$var_a\E$)(?=\Q$var_b\E$)(?=\Q$var_c\E$)/)
Of course, that only works because abcde meets the following conditions:

In other words, your "optimization", aside from being hard to read and probably being slower, has very limited usage.

It would be better to use:

my $match = 1; foreach ($var_a, $var_b, $var_c) { next if /abcdefgh/; $match = 0; last; } if ($match) { ... }

or

if ((grep /abcdefgh/, $var_a, $var_b, $var_c) == 3) { ... }

or

use List::MoreUtils qw( all ); if (all { /abcdefgh/ } $var_a, $var_b, $var_c) { ... }

The grep solution is easier to read than the foreach solution, but it has the disadvantage of always executing the regexp for every item in the list. The foreach and the all solutions execute the regexp as few times as possible

(Pardon the lateness of my reply; I was on vacation.)

Replies are listed 'Best First'.
Re^5: howto make a very long IF statment shorter
by johngg (Canon) on Jul 11, 2006 at 20:28 UTC
    I hope you had an enjoyable and restful vacation.

    As you probably guessed, it wasn't a serious proposal but just a bit of noodling around for fun, finding out what could be achieved. I think Herkum stated in this thread that if you wanted to match an exact literal then the eq comparator would be quicker than firing up the regex engine. That is how I would probably attack it in the real world.

    Cheers,

    JohnGG