Perl - Part 9
[home] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25]
if Construct Continued: Task 006
The last program made no output if the user did not satisfy the age condition of the program. This is unsatisfactory. Programs should always give some form of out put if only to say the user is wrong! Modify the program to cope with the alternate scenario, where the user is too young to vote:

When you run the program now, you should get output for all three possible age conditions:
- Less than 18.
- Age equal to 18.
- Age greater than 18.
Improving & and extending the use of the if function
The program as given above copes with all voting entitlement outcomes. The ge in the first if takes care of possibilities 2 & 3 above. The second if, with lt, caters for the remaining possibility, no. 1 above.
If you think about it though, since two of the three possibilities are covered, the 1st option must be all that remains after the 1st if statement. So why run a test using an if to check that it's valid?
This is a clearly unnecessary test so most programming languages offer a better way to do things, the if...else construct. Perl provides this also.
To see this change the line:
if ($age lt 18)
to
else
Your program should now work as before, but with less computational overhead. Note how items in the {...} pairs - which are code blocks - are further indented. Use this indentation as shown. This indentation gives a visual indicator of the program structure and greatly assists with, amongst other things, debugging.
More anon...
[home] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25]
Last updated: 20131015-16:45