Text or Number

Joshua Goodall joshua at roughtrade.net
Thu Mar 25 05:11:09 CST 2004


On Thu, Mar 25, 2004 at 04:46:49PM +1100, Scott Penrose wrote:
> Now I know I am being dumb here...
> 
> How can I find out that $x is a single character of ord 00-ff vs a 
> number:
> 
> 	That is - "1" does not eq chr(1);
> 
> The reason is that I get a log of people doing this
> 
> 	$pp->set_byte(0, 1);
> 
> And of course I set the value on the parallel port to ord("1").
> What I want to do is, if someone has given me a number - rather than a 
> string, that I convert it to a character.
> 	chr(1);
> 
> What is the safest way to do this ?

Alternates:

i) Use a statically typed language.

ii) Create a separate function for the alternative (set_chr?)
    and document very clearly the difference (perhaps with a 
    "WHICH FUNCTION SHOULD I USE" for the hopeless cases).

iii) (Slick) With the standard guts-analysing module, B:

use B qw(svref_2object);
sub cmpflags($$) { $_[1] & svref_2object($_[0])->FLAGS ? 1 : undef }
sub isinteger($) { cmpflags \$_[0], B::SVf_IOK | B::SVp_IOK }

A call in set_byte to isinteger($_[1]) or whatever will return 1
if the underlying perl scalar was originally an integer.


(Although be aware and beware of this example, which demonstrates
how the perlguts squirm:

#!/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);
}

see perldoc B, and perlguts :))

- joshua.

-- 
Joshua Goodall                           "as modern as tomorrow afternoon"
joshua at roughtrade.net                                       - FW109
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 187 bytes
Desc: not available
Url : http://mail.pm.org/archives/melbourne-pm/attachments/20040325/6a4a245e/attachment.bin


More information about the Melbourne-pm mailing list