Can someone explain what exactly the string "0 but true" means in Perl? As far as I understand, it equals zero in an integer comparison, but evaluates to true when used as a boolean. Is this correct? Is this a normal behavior of the language or is this a special string treated as a special case in the interpreter?
False Values: Empty string or string contains single digit 0 or undef value and zero are considered as the false values in perl.
Perl has a number of values that are considered "false": undef , zero, the string "0" , the empty string, a special boolean value that morphs into the empty string or the empty list depending on context, and objects that are overloaded for boolean context.
It's normal behaviour of the language. Quoting the perlsyn
manpage:
The number
0
, the strings'0'
and""
, the empty list()
, andundef
are all false in a boolean context. All other values are true. Negation of a true value by!
ornot
returns a special false value. When evaluated as a string it is treated as""
, but as a number, it is treated as0
.
Because of this, there needs to be a way to return 0
from a system call that expects to return 0
as a (successful) return value, and leave a way to signal a failure case by actually returning a false value. "0 but true"
serves that purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With