Text or Number

Andrew Savige ajsavige at yahoo.com.au
Sat Mar 27 19:25:32 CST 2004


Joshua Goodall <joshua at roughtrade.net> wrote:
> #!/usr/bin/perl
> use B qw(svref_2object);
> sub cmpflags($$) { $_[1] & svref_2object($_[0])->FLAGS ? 1 : undef }
> sub isinteger($) { cmpflags \$_[0], B::SVf_IOK | B::SVp_IOK }
> sub isstring ($) { cmpflags \$_[0], B::SVf_POK | B::SVp_POK }
> 
> $a=42; $b=$a; $c=$a; $d="$c";
> for $i ($a, $b, $c, $d) {
>     printf "%2s: int=%1s str=%1s\n", $i, isinteger($i), isstring($i);
> }

for $i ($a, $b, $c, $d) {
    my $is_string = (~$i & $i) ne '0';
    printf "%2s: int=%1s str=%1s\n", $i, !$is_string, $is_string;
}

This old merlyn trick exploits that bitwise operators ~ and & operate
differently on numbers and strings. Notice that Joshua's prints:

42: int=1 str= 
42: int=1 str= 
42: int=1 str=1
42: int=  str=1

while merlyn's trick prints:

42: int=1 str= 
42: int=1 str= 
42: int=1 str= 
42: int=  str=1

Why the difference? Also, I'm curious to know which type of applications
care about this (in the original question, I didn't understand exactly
how this was causing trouble).

/-\


Find local movie times and trailers on Yahoo! Movies.
http://au.movies.yahoo.com



More information about the Melbourne-pm mailing list