Questions about this topic? Sign up to ask in the talk tab.

Perl/Basics/Boolean Logic/Statements

From NetSec
Jump to: navigation, search

Perl > Basics > Boolean Logic > Statements


An if statement may have 3 types of clauses: if,elsif, and else. For the below example, assume that the $age scalar is passed as a command line argument:

if (int($age) == $age) {  #Making sure it's an integer.
    if ($age < 18) {      #If the age is less than 18:
        print "You must be at least 18 to view this.\n";
    } elsif ($age < 21) { # If the age is more than 18, but less than 21:
        print "Because you are under 21, some features may be restricted.\n";
    } else {              # If none of the conditions have been met:


An unless statement may only have the unless clause and an else clause.

unless ($age >= 21) {
    print "All content is restricted for users under the age of 21.\n";
} else {
    print "Welcome to our sample age gate!\n";

AND and OR

"And" and "or" are used to apply multiple conditions to a boolean statement.

  • && is the way perl represents "and"
  • || is the way perl represents "or"


  if ($age < 21 && $age >= 18) {
      print "Some content will be restricted because you are not older than 21.\n";


To use perl's switch() routine you must have use Switch; before your switch() statement. A switch statement allows a programmer to avoid long chains of "elsif" statements. It condenses the amount of required lines of code. Perl's switch statement is very similar to the switch() statement in C and C++, though the syntax is a little different. A perl switch() statement may contain case and else clauses. Perl switch cases can also be used to determine if a value is in a list, an array element, hash key, or matches a regular expression or string. In this example, suppose $option was a numeric value for an integer based menu with 3 options.

use Switch;
switch(int($option)) {
    case 1 {  # Essentially the same as if ($option == 1)
        print "You picked option 1!\n";
    case 2 { # Essentially the same as elsif ($option == 2)
        print "You picked option 2!\n";
    case 3 { # Essentially the same as elsif ($option == 3)
        print "You picked option 3!\n";
    else { 
        print "invalid menu option!\n";

For more information, see perldoc switch, or: here.


The term golfing applies to condensing a boolean statement into one line. Golfing is typically used when you only need to execute one line of code for a boolean statement.

print "You are not 18 or older!\n" unless ($age >= 18);
  • Is essentially the same as:
print "You are not 18 or older!\n" if ($age < 18);
  • Is essentially the same as this un-golfed statement:
unless ($age >= 18) {
    print "You are not 18 or older!\n";