Created
October 24, 2012 19:05
-
-
Save kraih/3948157 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
While this does detect what perl internals returns as booleans, there is nothing special about them.