Juerd has asked for the wisdom of the Perl Monks concerning the following question:

undef, 0, "0" and "" are false, so "0 but true" is pretty obvious and much seen.

I don't think there is a "1 but false", but if there is, please let me know :)

(I'm afraid I'll have to wait for Perl6...)

2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Replies are listed 'Best First'.
Re: 1 but false
by robin (Chaplain) on Jan 08, 2002 at 00:55 UTC
    You're right, there isn't a "1 but false" ordinarily. You can make one though:
    my $one_but_false = OneButFalse->new(); print "value = $one_but_false\n"; print "truth = ", ($one_but_false ? "true\n" : "false\n"); package OneButFalse; use overload '0+' => sub {1}; use overload 'bool' => sub {0}; use overload fallback => 1; sub new { my ($pkg) = @_; bless {}, $pkg; }
    See What is truth? for more info.
Re: 1 but false
by blakem (Monsignor) on Jan 08, 2002 at 00:55 UTC
    One of the first really clever nodes I stumbled upon at the monastery was "Falsify" scalar strings by Fastolfe which can create "1 but false" as well as "I'm an error message - but false" which was its original intention... While not meant for production code, it does address your question.

    -Blake

Re: 1 but false
by danger (Priest) on Jan 08, 2002 at 01:23 UTC

    Another way is to use a dualvar() (from Scalar::Util) for such a purpose:

    use Scalar::Util qw/dualvar/; my $x = dualvar(1,"0"); $y = $x + 41; print "$y\n"; # 42 print "Str \$x: $x\n"; print "Num \$x: ", $x + 0, "\n"; if($x + 0){print "\$x + 0 is true\n"} unless($x){print "\$x is false\n"} __END__ prints: 42 Str $x: 0 Num $x: 1 $x + 0 is true $x is false
Re: 1 but false
by derby (Abbot) on Jan 08, 2002 at 01:02 UTC
    juerd,

    I'm not sure why you would want a "1 but false" return value. The "0 but true" value is perl sugar for those cases where the underlying library returned 0 for true values and -1 for errors (ioct, fcntl, shmctl, etc). About the only place I've seen 1 be a "false" value is not for API calls but for exit statuses and then there's normally a range of positive exit values that indicate what the failure is (and 0 would be normal exit).

    -derby