SamPointer has asked for the wisdom of the Perl Monks concerning the following question:

I won't go into too much detail about why I am doing what I am doing, because I'm sure you've all got better things to do :).

I am tryin to write a piece of code that will take two values, add them together and print them out. Ah, simple you might think. But, I want to take my input as raw unsigned binary and perform the arithmetic on it. The problem that I am having is that perl is being too clever!

Say for example I enter 2 parameters as '1' and '2' (ascii codes 0x31 and 0x32 hex) and put them into two scalars. I add the scalars together `$a + $b`. I want the result of the sum of the two scalars to be returned as 0x61 hex, *not* '3'.

In summary, I want to prevent any interperation of data within scalars and to preserve raw binary input.

I also would very much like it if I could prevent a scalar from exceeding the value of 0xF, thereby ensuring that it behaves as a single byte all of the time; and throws an exception when trying to place a value that is too large into the it.

Many thanks. If I haven't defined the problem clearly enough then please say so, I am grateful for any help.

Replies are listed 'Best First'.
•Re: How to prevent perl from being clever
by merlyn (Sage) on Oct 29, 2002 at 14:45 UTC
    Well,
    my @bytes = unpack "C*", $a;
    will get you an array with (0x31) in it. If you do the same to $b you can then add them together byte by byte in parallel, ensuring that no single value is greater than 255. When you are done:
    my $result = pack "C*", @newbytes;
    will give you a single string. Of course, this string is likely to be fairly un-terminal-able. {grin}

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: How to prevent perl from being clever
by jmcnamara (Monsignor) on Oct 29, 2002 at 15:39 UTC

    You should be able to use the ord and chr functions (or pack/unpack "C") to do what you want:
    my $sum = ord(1) + ord(2); printf "0x%x\n", $sum; print chr $sum, "\n"; __END__ prints: 0x63 c

    --
    John.