next up previous contents index
Next: Variable scoping Up: Conditionals Previous: Regular Expressions   Contents   Index


if() { } and unless(){ }

The simplest form of a conditional is a single if() statement:
my $age = 22;
if ($age < 30) {
  print "You probably don't remember the Beatles, do you?";
}
Here, the truthfulness of the statement within round brackets is evaluated, and if it's true, the statements within the curly braces are carried out. If, as in this example, there is only one such statement, this can be shortened to
my $age = 22;
print "You probably don't remember the Beatles, do you?"
  if ($age < 30);
which, at times, may be more readable.

Sometimes, it may be more natural to specify the falseness of some statement as a condition to carry out a set of commands. For this you can use an unless statement:

my $age = 22;
unless ($age >= 30) {
  print "You probably don't remember the Beatles, do you?";
}
This too may be abbreviated if there's only one statement to be carried out:
my $age = 22;
print "You probably don't remember the Beatles, do you?"
  unless ($age >= 30);


Subsections