Need some conditional help.

They have: 62 posts

Joined: May 2000

I want a shortcut regarding the search of two or more different variables using the same regex. I know you can do...

if ($var1=~/blah/ && $var2=~/blah/ && $var3=~/blah/) {
print "blah";
}
'

I'd like to simplify this. Is there a way?

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

I don't thinks so.
I think you can only look for two strings inside of one, not one string inside of two.
Make sense?

They have: 1,587 posts

Joined: Mar 1999

depends on how many variable u have. if u have tons u may want to use foreach.

They have: 161 posts

Joined: Dec 1999

You might think it would be a good idea to do this:

$a = "jeff";
$b = "mary";
$c = "anna";
$all = join "", map "!$_", $a, $b, $c;
# $all is now "!jeff!mary!anna"
# we assume there are no !'s in the $a, $b, $c variables

if ($all =~ /![aeiou]/) {
  print "at least one of the names starts with a vowel\n";
}
'

But this does more work than is needed. You've just gone through each of your variables TWICE BEFORE you get to the regular expression! Compare that to:

for ($a, $b, $c) {
  if (/^[aeiou]/) {
    print "at least one of the names starts with a vowel\n";
    last;
  }
}
'

That is far more efficient.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.