2.6. The if Control StructureOnce you can compare two values,you'll probably want your program to make decisions based upon that comparison. Like all similar languages,Perl has an if control structure: if ($name gt 'fred') { print "'$name' comes after 'fred' in sorted order./n"; } If you need an alternative choice,the else keyword provides that as well: if ($name gt 'fred') { print "'$name' comes after 'fred' in sorted order./n"; } else { print "'$name' does not come after 'fred'./n"; print "Maybe it's the same string,in fact./n"; } Those block curly braces are required around the conditional code (unlike C,whether you know C or not). It's a good idea to indent the contents of the blocks of code as we show here; that makes it easier to see what's going on. If you're using a programmers' text editor (as discussed in Chapter 1),it'll do most of the work for you. 2.6.1. Boolean ValuesYou may use any scalar value as the conditional of the if control structure. That's handy if you want to store a true or false value into a variable,like this: $is_bigger = $name gt 'fred'; if ($is_bigger) { ... } But how does Perl decide whether a given value is true or false? Perl doesn't have a separate Boolean data type as some languages have. Instead,it uses a few simple rules:[*]
There's one trick hidden in those rules. Because the string '0' is the same scalar value as the number 0,Perl has to treat them the same. That means that the string '0' is the only nonempty string that is false. If you need to get the opposite of any Boolean value,use the unary not operator,!. If what follows it is a true value,it returns false; if what follows is false,it returns true: if (! $is_bigger) { # Do something when $is_bigger is not true } |
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。