Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

"Falsify" scalar strings

by Fastolfe (Vicar)
on Jan 26, 2001 at 04:01 UTC ( [id://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__);
}

1;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: sourcecode [id://54436]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-03-19 10:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found