Previous Operators |
CGI-Perl Tutorial Control Flow - If |
Next Control Flow - for |
Every windows user knows the flow of control. It is usually Control-Alt-Delete. But in programming we have the control. Let us get acquainted with some loops and conditions.
I don't know what would have become of the computer industry if the 'if' condition was not there. I don't think that there is one proper program without the if condition - except for those tiny 'Hello World' programs.
Syntax:if ( condition ) {
statement
}
elsif ( condition ) {
statement
}
else {
statement
}
The operators that we discussed in the previous chapter is of much use in if conditions.
if ( $i == 5) { statement; }
will execute the statement if the variable '$i' has the value 5.
The 'If' condition checks the condition and if it is true, then it will execute the statement. If not it will check the next 'elsif' condition. If no given conditions are true, it will execute the statement in else(if 'else' is present).
On to our first example....
#!/usr/local/bin/perl print "Here's some descriptions of airplanes run by various OS...\n"; $OS = "DOS"; #Change this to different OS Names print "Our OS is $OS. So our plane will be like this...\n"; if ( $OS eq "DOS" ) { print "Everybody pushes it till it glides, then jumps on and lets it coast till it skids, then jumps off, pushes, jumps back on, etc."; } elsif ( $OS eq "Macintosh") { print "All the flight attendants, captains and baggage handlers look the same, act the same and talk the same. Every time you ask a question, you are told you don't need to know, don't want to know and everything will be done for you without your knowing, so just shut up."; } elsif ( $OS eq "Windows") { print "Colorful airport terminal, friendly flight attendants, easy access to a plane, uneventful takeoff. Then: BOOM! You blow up without any warning whatsoever."; } elsif ( $OS eq "Unix") { print "Everyone brings one piece of the plane. Then they go on the runway and piece it together, all the while arguing about what kind of plane they're building."; } else { print "General Error: No Plane."; }
You would have noticed that the operator used is 'eq' and not '=='($OS eq "Unix" and not $OS == "Unix"). This is because we are comparing stings - not numbers. For numbers, '==' operator must be used.
Previous Operators |
Contents | Next Control Flow - for |