Bobby
Bobby

Reputation: 79

Structure or syntax for empty if/elsif/else block in perl

This amounts to testing for xor (one or the other but not both and not neither) where the task demands something is done for the one but not for the other but we abandon the project if both or neither.

This example might be most to the point but the empty block doesn't sit well with me

if (condition == 1) {
  do something
}
elsif (condition == 2) {
  ; # do nothing aka carry on
}
else {
  exit;
}

Nesting seems no better and in this example misses (ie, does not validate) the second condition

if (condition) {
  if (condition == 1) {
    do something
  }
}
else {
  exit;
}

Combining both of the above avoids the empty block and will work but forces redundant testing and seems inefficient.

if ((condition == 1) || (condition == 2)) {
  if (condition == 1) {
    do something
  }
}
else {
  exit;
}

Is there an alternative I haven't thought of? Why might one choose one structure over another? Thanks for your insights.

Upvotes: 0

Views: 442

Answers (2)

Holli
Holli

Reputation: 5072

my %dispatch = {
    1 => sub { dosomething() },
    2 => sub { dosomethingelse() },
}

exists $dispatch{$condition}  ?
    $dispatch{$condition}->() :
    do_default();

Upvotes: 0

ikegami
ikegami

Reputation: 385657

if (condition == 1) {
  do something
}
elsif (condition == 2) {
  ; # do nothing aka carry on
}
else {
  exit;
}

and

if ((condition == 1) || (condition == 2)) {
  if (condition == 1) {
    do something
  }
}
else {
  exit;
}

are equivalent to

if (condition == 1) {
  do something
}
elsif (condition != 2) {
  exit;
}

None of the above test for "one or the other but not both and not neither". For that, you'd need the following:

if (condition == 1 || condition == 2) {
  do something
}

Since condition can't be both 1 and 2, no further checks are needed. On the other hand, if you had two independent conditions, you could literally use xor.

if (condition1 xor condition2) {
  do something
}

Warning: This is a low-precedence operator (like not, and and or), so you may need to put parens around both of the expressions it has for operands.

Upvotes: 4

Related Questions