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

I am writing a Perl program that sends and receives messages from two sockets and acta as a switch. I have to modify the received messages received from one socket, prepend 3 bytes to the data, and finally send the modified messages to another socket. I adopt select()...sysread()...syswrite() mechanism to poll for messages between sockets. The received messages are stored in $buffer during modification.
Now I can use following way to get the received messages:
my $hexmsg = unpack("H*", $buffer); my @msg = ( $hexmsg =~ m/../g );

then I can insert 3 bytes to @msg using splice(). However, I don't know how to pack the message in @msg into a scalar(such as $buffer) and send it to another socket by syswrite().
I know this method is fool and I believe there must be more clever ways. Can anybody help me with this problem? Thank you in advance!
BTW, are messages in $buffer binary?

Replies are listed 'Best First'.
Re: How can I modify received socket messages in Perl?
by ikegami (Patriarch) on Mar 09, 2009 at 15:15 UTC

    First, I doubt your $buffer contains a message, except by luck. But if it does, why not just do

    $buffer = "\x{12}\x{34}\x{56}" . $buffer;
    or equivalent
    $buffer = (map chr, 0x12, 0x34, 0x56) . $buffer;

    BTW, are messages in $buffer binary?

    Assuming $buffer is being populated by sysread, $buffer is a string where each character represents a byte.

      I am sorry that I didn't tell things clearly. I just want to insert 3 bytes into received msg between the header and body, but not in the front or end.

      Can substr() work?
        You don't have a header and body, just a bunch of bytes. First things first, you need to identify the header and the body.
Re: How can I modify received socket messages in Perl?
by Anonymous Monk on Mar 09, 2009 at 15:14 UTC
    then I can insert 3 bytes to @msg using splice(). However, I don't know how to pack the message in @msg into a scalar(such as $buffer) and send it to another socket by syswrite().
    $bytes = "\0\0\0"; $buffer = $bytes . $buffer;
    syswrite