SoFunction
Updated on 2025-04-07

In-depth study on truth and falsehood in Perl

Perl believes that the truth value is self-evident, indicating that the truth value of anything can be calculated. Perl defines the truth value in a practical way, that is, the truth value of an entity depends on the type of the entity. Perl always optimistically believes that there are far more real things in this world than fake things.

Perl is different from any other computer language. Perl is created by linguists, and the meaning of language cannot be separated from the context. Therefore, the truth value in Perl can be calculated in scalars (scalar $ and array @ are similar to the singular and plural in English, book and books. In the real world, the truth value should be singular, so it is a scalar). In addition, no type of casting will be done (such as int('42') in Python to convert the character type containing numbers into an int type, and in Java (int)'d' converts the character type into an integer).

For various types of values ​​in scalars, the rules are as follows:

Character type: Except for "" and "0", all characters are true (true)
Number type: All numbers except 0 are true
Reference type: All references are true (all references will point to an object with an address, which will definitely not be 0, because it is definitely defined)
Undefined: All undefined values ​​are false

The following examples can easily understand the concepts of true and false in Perl:

Copy the codeThe code is as follows:

0          # Convert to string "0", so it is false
1          # Convert to string "1", so it is true
100 - 100   # 100-100 equals 0, which will convert to the string "0", so it is false
0.00        # Equal to 0, it will be converted to the string "0", so it is false
"0"        # String "0", so it is false
""         # This is an empty string, so it is false
"0.00"      # That is, it is not "" nor "0", so it is true
"0.00" + 0 # Cast converted by +, the calculation result is 0, so it is false
\$a         # Reference to the scalar $a, so it is true, even if $a is false.
undef()     # is a function that returns an undefined value, so it is false