1. Technology

Conditionals - How to make decisions in Perl

Conditionals - if

By

Man using computer
E Dygas/Photodisc/Getty Images
Next: Conditionals - else, elsif

A conditional is a control structure that will activate specific blocks of your code based upon whether your specified statement (or expression, or condition) evaluates to true or false. You can use these conditional statements to make logical decisions, or take specific actions based on available data. Much like a loop, the conditional statement is a pretty basic structure in perl and programming in general, and you will find a vast amount of opportunities to use them.

The first conditional we're going to look at is the if statement. Like all conditionals, the statement you write will be evaluated to true or false, and if the statement is true, the block of code will be executed. If the statement evaluates to false, however, the block is ignored. As you will see from the examples, all our conditionals use the comparison operators pretty heavily in the statements to run these tests on the data.

Let's take a look at a simple if statement:

 for ($count = 1; $count <= 10; $count++) {
 print "counter: $count\n";
 if ($count == 5) {
 print "The counter is currently equal to 5.\n";
 }
 } 
What we've got here is a simple for loop that runs the $count variable from a value of 1 to 10, incrementing it by 1 each time it goes through the loop. Every time it cycles the loop, it prints the value of $count so you can see it. After the print statement, you'll see our if conditional. The statement inside the parenthesis is evaluated every single time the loop is executed, but the block that it surrounds is only executed if the statement evaluates to true. The output looks like this:
 counter: 1
 counter: 2
 counter: 3
 counter: 4
 counter: 5
 The counter is currently equal to 5.
 counter: 6
 counter: 7
 counter: 8
 counter: 9
 counter: 10 
At only one point in the loop does the expression actually evaluate to true. When $count is equal to 5, it executes the code block and prints the line "The counter is currently equal to 5".

Next: Conditionals - else, elsif

  1. About.com
  2. Technology
  3. Perl
  4. Perl Tutorials
  5. Perl conditionals tutorial - Conditionals in Perl, how to make decisions and branch code in your Perl scripts with conditionals.

©2014 About.com. All rights reserved.