exit code - There's "0 but true", but is there "42 but false" in perl? -


as per question. know there's "0 true" true in boolean context false otherwise, can return false in boolean context non-zero value (the obvious place return statuses 0 success , else error).

no. (except fun dualvars , overloaded objects)

the truthiness of perl scalar depends on string value. if no string value present, numeric field used.

false values are: undef, "", 0, , avoid issues testing stringification first: "0".

not numerically 0 evaluates false: "0e0" true, more self-documenting "0 true". latter special-cased avoid non-numeric warnings.

however, enter dualvars. numeric , stringy field of scalar don't have in sync. common dualvar $! variable errno in numeric context, error string containing reason string. possible create dualvar numeric value 42 , string value "", evaluate false.

use scalar::util qw/dualvar/;  $x = dualvar 42, ""; $x;   # empty string 0+$x; # force numeric: 42 $x ? 1 : 0; # 0 

and overloaded objects. instances of following class stringify nicely, still evaluate false in boolean context:

package falsestring; sub new {   ($class, $str) = @_;   bless \$str => $class; } use overload   '""'   => sub { ${shift()} },   'bool' => sub { 0 }; 

test:

my $s = falsestring->new("foo"); $s; $s ? "true" : "false"; 

prints

foo false 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -