If statement consists a condition, followed by statement or a set of statements as shown below:
if(condition){ Statement(s); }
The statements gets executed only when the given condition is true. If the condition is false then the statements inside if statement body are completely ignored.
Example:
In the following example, we have an integer value assigned to variable “num”. Using if statement, we are checking whether the value assigned to num is less than 100 or not.
#!/usr/local/bin/perl printf "Enter any number:"; $num = <STDIN>; if( $num < 100 ){ # This print statement would execute, # if the above condition is true printf "num is less than 100\n"; }
Output:
Enter any number:78 num is less than 100
Nested if statement in perl
When there is an if statement inside another if statement then it is called the nested if statement.
The structure of nested if looks like this:
if(condition_1) { Statement1(s); if(condition_2) { Statement2(s); } }
Statement1 would execute if the condition_1 is true. Statement2 would only execute if both the conditions( condition_1 and condition_2) are true.
Example:
#!/usr/local/bin/perl printf "Enter any number: "; $num = <STDIN>; if( $num < 100 ){ printf "num is less than 100\n"; if( $num > 90 ){ printf "num is greater than 90\n"; } }
Output:
Enter any number: 99 num is less than 100 num is greater than 90
Leave a Reply