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

Perl/Basics/Boolean Logic/Statements/Switch

From NetSec
Revision as of 03:55, 20 September 2012 by Levi99Vmsb (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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.