[comp.lang.perl] using vec

jsb@cs.brown.edu (John Bazik) (02/28/91)

A quick question on the use of vec: given the following script:

	$i = $j = $k = 0;

	vec($i, 2, 1) = 1;
	vec($j, 3, 1) = 1;
	vec($k, 4, 1) = 1;

	print "i $i j $j k $k\n";

I get the following results:

	i 4 j 8 k 0

How come k isn't 16?
Are vectors supposed to make sense when used this way?

I'm at pl41.

John Bazik
jsb@cs.brown.edu

lwall@jpl-devvax.jpl.nasa.gov (Larry Wall) (03/14/91)

In article <66526@brunix.UUCP> jsb@cs.brown.edu (John Bazik) writes:
: A quick question on the use of vec: given the following script:
: 
: 	$i = $j = $k = 0;
: 
: 	vec($i, 2, 1) = 1;
: 	vec($j, 3, 1) = 1;
: 	vec($k, 4, 1) = 1;
: 
: 	print "i $i j $j k $k\n";
: 
: I get the following results:
: 
: 	i 4 j 8 k 0
: 
: How come k isn't 16?
: Are vectors supposed to make sense when used this way?

It makes sense if you realize that vec() isn't expecting you to supply
scalars with numeric values.  When it goes to fetch the pointer to
the vector string, the fetching routine automatically converts numeric 0
to "0", which sets bits 32 and 16 in the first byte of the string.
Saying

	vec($i, 2, 1) = 1;

then sets the 4 bit in that byte, so you change "0" to "4" (changing the
ASCII value of 48 to 52).  Likewise

	vec($j, 3, 1) = 1;

sets the 8 bit, so you get "8" (changing the ASCII value of 48 to 56).  But

	vec($k, 4, 1) = 1;

sets the 16 bit, which is already set, so you end up with "0".

Vectors are not intended to be set numerically, nor are they intended to
be printable--you just lucked out that you didn't end up with control
characters.  To turn bit vectors into printable strings, use unpack
with the b specifier (new with 3.044, I think).

Larry