Category: Code Development
Author/Contact Info David Nesting
Description: It came up in Nice style for interesting error messages that it might be useful to have a way to return a simple false value while still providing information about why it was false. Along those lines, I wrote this little module that "falsifies" a string, in that boolean tests will always come up false, even though the string can be used like any other. I don't think I really want to recommend this as a real solution to anyone's problem, since it does muck with the true/false semantics of scalars, in that a non-empty string is usually "true", so it may screw with the heads of people trying to use and maintain your code. But hey, I thought it was amusing. Any changes made to the string automatically remove this special property, and only strings may be used. If anyone has any ideas for trivial changes that would allow this to work with just about any type of scalar data, that might be useful, but for the purposes I had in mind this was sufficient in my head.

To use it:

use falsify; sub might_fail { return int(rand(2)) ? "All OK!" : falsify "Ruh-roh!"; } for (1..10) { my $returned = might_fail; print $returned ? "YES! $returned" : "No! $returned", "\n"; } my $false = falsify "Hello, world!"; # etc.
package falsify;

use strict;
use overload
        'bool'     => sub { 0 },
        '""'       => sub { ${$_[0]} },
        'fallback' => 1;

sub import {
        my $caller = caller;
        no strict 'refs';

        *{$caller."::falsify"} = \&falsify;

sub falsify {
        my $string = "".shift;  # force it to be a string
        my $self = \$string;
        bless($self, __PACKAGE__);