in reply to Re^2: howto make a very long IF statment shorter
in thread howto make a very long IF statment shorter
use strict; use warnings; my $w = q{}; my $x = q{}; my $y = q{}; my $z = q{}; cmpOr(); $x = q{abc}; cmpOr(); $z = q{abcdefghij}; cmpOr(); $z = q{abcdefgh}; cmpOr(); $y = q{abcdefgh}; cmpOr(); $z = q{abcdefghij}; cmpOr(); sub cmpOr { print qq{Comparing OR methods with:-\n}, qq{ \$w is ->$w<-\n}, qq{ \$x is ->$x<-\n}, qq{ \$y is ->$y<-\n}, qq{ \$z is ->$z<-\n}; if ($w =~ /abcdefgh/ || $x =~ /abcdefgh/ || $y =~ /abcdefgh/ || $z =~ /abcdefgh/) { print qq{ orig: true\n}; } else { print qq{ orig: false\n}; } if (q{abcdefgh} =~ /^(?:$w|$x|$y|$z)$/) { print qq{johngg: true\n}; } else { print qq{johngg: false\n}; } print qq{\n}; }
When run this produces
Comparing OR methods with:- $w is -><- $x is -><- $y is -><- $z is -><- orig: false johngg: false Comparing OR methods with:- $w is -><- $x is ->abc<- $y is -><- $z is -><- orig: false johngg: false Comparing OR methods with:- $w is -><- $x is ->abc<- $y is -><- $z is ->abcdefghij<- orig: true johngg: false Comparing OR methods with:- $w is -><- $x is ->abc<- $y is -><- $z is ->abcdefgh<- orig: true johngg: true Comparing OR methods with:- $w is -><- $x is ->abc<- $y is ->abcdefgh<- $z is ->abcdefgh<- orig: true johngg: true Comparing OR methods with:- $w is -><- $x is ->abc<- $y is ->abcdefgh<- $z is ->abcdefghij<- orig: true johngg: true
In the particular circumstance of wanting each variable to match the string exactly, this method could save a deal of typing but it's no use in the general case as you pointed out.
Just out of curiosity I had a try at an alternative to if ( $var_a =~ /^abcde$/ && $var_b =~ /^abcde$/ && .... This is what I came up with.
if (q{abcde} =~ /^(?=$var_a$)(?=$var_b$)(?=$var_c$)/)
Cheers,
JohnGG
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: howto make a very long IF statment shorter
by ikegami (Patriarch) on Jul 11, 2006 at 16:50 UTC | |
by johngg (Canon) on Jul 11, 2006 at 20:28 UTC |