"Perl for Perl Newbies" - Part 1Conditionals

7. Conditionals

Conditionals enable us to execute a group of statements if a certain condition is met. For example the following program, reports to the user whether or not his name starts with the letter "A":

print "Please enter your name:\n";
$name = <>;
if (substr($name,0,1) eq "A")
{
    print "Your name starts with 'A'!\n";
}
else
{
    print "Your name does not start with 'A'!\n";
}

The code substr($name,0,1) eq "A" is a condition expression which uses the perl eq operator, which returns true if and only if the strings are the same. There are more such operators and they will be explained shortly.

Inside the curly brackets following the if there is the code to be executed by the conditional. That code can be as long as you like. The else part is executed assuming the conditional was found to be false, and is optional.


Written by Shlomi Fish