next up previous contents index
Next: if/elsif/else and switch statemements Up: Conditionals Previous: Variable scoping   Contents   Index


if/else and ternary operators

There may be times when you want to carry out some statements if a certain condition is met, and then do something else if it's not met. For this you can use an if() { } else { } block:
my $age = 22;
if ($age < 30) {
  print "You probably don't remember the Beatles, do you?";
}
else {
  print "You do remember the Beatles, don't you?";
}

For simple if() { } else { } statements it may be possible to use a ternary operator. As an illustration, the following code:

my $income = 50000;
my $tax_rate;
if ($income < 80000) {
  $tax_rate = 0.3;
else {
  $tax_rate = 0.5;
}
can be written as
  my $income = 50000;
  my $tax_rate = ($income < 80000) ? 0.3 : 0.5;
There are three parts to the ternary assignment
$var =  condition ? if_true : if_false