[comp.lang.perl] Differentiating strings and numbers in an array?

sondeen@isi.edu (Jeff Sondeen) (01/31/91)

I want to add an offset to the numbers in an array that contains both
numbers and strings, like (0,"b",1) -> (3,"b",4), but I can't differentiate
the numeric 0's from the strings that have numeric value 0.  Can it be done
or should I try some other limb?  Thanks, /jeff
-- 

/jeff	sondeen@isi.edu				"engineers were discouraged
		from bringing problems to the attention of their supervisors"
	-- John Magnus, final report, Hubble Space Telescope investigation

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (02/01/91)

In article <16574@venera.isi.edu> sondeen@venera.isi.edu (Jeff Sondeen) writes:
: I want to add an offset to the numbers in an array that contains both
: numbers and strings, like (0,"b",1) -> (3,"b",4), but I can't differentiate
: the numeric 0's from the strings that have numeric value 0.  Can it be done
: or should I try some other limb?  Thanks, /jeff

In general, Perl tries to make it difficult to tell any difference between
a string and a numeric value.  It is possible, however:

    vec($dummy,0,1);	# enable vector operations
    srand;
    $foo = rand() < .5 ? 0 : "0";
    $bar = "1xxxxxxxxxxxxxxxxxxxxx";	# make long enough

    if (length($foo | $bar) == length($bar)) {
	print "string\n";
    }
    else {
	print "numeric\n";
    }

Vector operations revert to numeric operations if either operand has
a numeric value.  The numeric value of $bar is 1, and that will make 32
bits or less of result.  But it doesn't get evaluated as a number unless
$foo has a numeric value.  Note that $bar must be reinitialized each time,
since if the test fails it evaluates $bar in a numeric context, which will
cause the test to fail next time.  There may be more succinct ways.

This is heavy wizardry, and if you don't understand it, don't worry
about it.  It's probably better to find some other way to do what you
want anyway.  I can't imagine getting myself into a situation in which I'd
want to tell the difference between 0 and "0"--it's like wanting to
differentiate -0 and +0 on a 1's complement machine--I'd just as soon
let the machine worry about it.

Larry