> -----Original Message-----
> From: Shaun Fryer [mailto:[EMAIL PROTECTED]]
> Sent: Tuesday, April 23, 2002 4:15 PM
> To: Perl Beginners
> Subject: evaluating multiple conditions
>
>
> Is there a simple way to evaluate multiple conditions in an if or
> unless statement? For example take the following very simple example.
>
> if (($something eq 'string0') || ($something eq 'string1') ||
> ($something =~ /string2/)) {
> &do_something;
> } else {
> &do_somthing_else;
> }
This code doesn't need to be fixed. For style, I would remove the inner
parens (unnecessary) and change the function calls to do_something()
instead of the (old-style) &do_something.
But your handling of the condition is fine. If you want to make it more
readable, you could format it as:
if ($something eq 'string0'
|| $something eq 'string1'
|| $something =~ /string2/) {
>
> Being a bit of a spartan I think it would be nice if I could do it
> like the following instead.
>
> if ($something eq ('string0' || 'string1' || =~ /string2/)) {
> &do_something;
> } else {
> &do_somthing_else;
> }
>
> But the latter doesn't seem to work.
It doesn't work, because it's not equivalent. It also contains
a syntax error.
> So, as a kluge I've been doing as
> follows.
>
> my $test_ok;
> $test_ok = 1 if ($something eq 'string0');
> $test_ok = 1 if ($something eq 'string1');
> $test_ok = 1 if ($something =~ /string2/);
> if ($test_ok) {
> &do_something;
> } else {
> &do_somthing_else;
> }
How is this better? It's actually slower, because every test is evaluated.
In your original formulation, the entire expression would become true
as soon as the first sub-expression was true. Also, this one needs
an intermediate variable, and is harder to read.
>
> Is there a better way to simplify the syntax when testing for multiple
> conditions?
Your original code is the proper way to do it. All the other solutions
proffered are inferior, IMO.
The suggestion of:
if($something =~ /^(string0|string1|string2)$/)
is not equivalent to your original condition. It's also likely to be
inefficient.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]