ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
4.2 The if/unless StatementNext up in order of complexity is the if ( (If you're a C or Java hacker, you should note that the curly braces are required. This eliminates the need for a "confusing dangling else" rule.) During execution, Perl evaluates the control expression. If the expression is true, the first block (the But what constitutes true and false? In Perl, the rules are slightly weird, but they give you the expected results. The control expression is evaluated for a string value in scalar context (if it's already a string, no change, but if it's a number, it is converted to a string[1]). If this string is either the empty string (with a length of zero), or a string consisting of the single character 0 # converts to "0", so false 1-1 # computes to 0, then converts to "0", so false 1 # converts to "1", so true "" # empty string, so false "1" # not "" or "0", so true "00" # not "" or "0", so true (this is weird, watch out) "0.000" # also true for the same reason and warning undef # evaluates to "", so false
Practically speaking, interpretation of values as true or false is fairly intuitive. Don't let us scare you. Here's an example of a complete print "how old are you? "; $a = <STDIN>; chomp($a); if ($a < 18) { print "So, you're not old enough to vote, eh?\n"; } else { print "Old enough! Cool! So go vote!\n"; $voter++; # count the voters for later } You can omit the print "how old are you? "; $a = <STDIN>; chomp($a); if ($a < 18) { print "So, you're not old enough to vote, eh?\n"; } Sometimes, you want to leave off the "then" part and have just an print "how old are you? "; $a = <STDIN>; chomp($a); unless ($a < 18) { print "Old enough! Cool! So go vote!\n"; $voter++; } Replacing If you have more than two possible choices, add an if ( Each expression (here, |