Skip to content

Instantly share code, notes, and snippets.

@kraih
Created October 24, 2012 19:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kraih/3948157 to your computer and use it in GitHub Desktop.
Save kraih/3948157 to your computer and use it in GitHub Desktop.
use warnings;
use strict;
use feature ':5.10';
use B;
# Type and flags for reference
my $obj = B::svref_2object(\(my $dummy = !!1));
my $TYPE = $obj->SvTYPE;
my $FLAGS = $obj->FLAGS;
sub looks_like_bool {
my $bool = shift;
# Compare type
my $obj = B::svref_2object(\$bool);
return !!0 unless $obj->SvTYPE == $TYPE;
# Compare flags
return !!0 unless $obj->FLAGS == $FLAGS;
# True value
return !!1 if $bool eq !!1;
# False value
return !!1 if $bool eq !!0;
# Not a boolean
return !!0;
}
say 'Boolean true' if looks_like_bool !!1;
my $true = !!1;
say 'Boolean true' if looks_like_bool $true;
say 'Boolean false' if looks_like_bool !!0;
my $false = !!0;
say 'Boolean false' if looks_like_bool $false;
say 'Random string' unless looks_like_bool 'whatever';
say 'Zero' unless looks_like_bool 0;
say 'One' unless looks_like_bool 1;
say 'Random integer' unless looks_like_bool 23;
say 'Random float' unless looks_like_bool 23.23;
@gbarr
Copy link

gbarr commented Oct 25, 2012

While this does detect what perl internals returns as booleans, there is nothing special about them.

my $y = 11.5 - 10.5;
my $tmp = 1+$y;
$tmp = "$y";

say "Generated Boolean" if looks_like_bool($y);

@kraih
Copy link
Author

kraih commented Oct 25, 2012

@gbarr You sunk my battleship.

@marcusramberg
Copy link

<3 @gbarr

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment