Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

"Falsify" scalar strings

by Fastolfe (Vicar)
on Jan 26, 2001 at 04:01 UTC ( #54436=sourcecode: print w/replies, xml ) Need Help??
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__);

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: sourcecode [id://54436]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2017-05-25 04:20 GMT
Find Nodes?
    Voting Booth?