Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

"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__);
}

1;
Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: sourcecode [id://54436]
help
Chatterbox?
[Corion]: Meh. Some Open Source people get bought out by advertising firms to change their projects to include advertising. But nobody has approached me to buy out WWW::Mechanize ::$browser from me, to make the browsers launch an ad page ...
[Corion]: ... instead of about:blank, which the modules currently do at startup.

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2017-07-24 14:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I came, I saw, I ...
























    Results (354 votes). Check out past polls.